dce dce - 1 month ago 7
Swift Question

Swift override static method compile error

I have these two swift classes:

class A {
static func list(completion: (_ result:[A]?) -> Void) {
completion (nil)
}
static func get(completion: (_ result:A?) -> Void) {
completion (nil)
}
}


class B: A {
static func list(completion: (_ result:[B]?) -> Void) {
completion (nil)
}
static func get(completion: (_ result:B?) -> Void) {
completion (nil)
}
}


Trying to compile this raise the error "overriding declaration requires an 'override' keyword" but just for the 'get' method of class B. 'list' method compiles fine. What is the difference between [B]? and B? for the compiler in this case?

Edit: Also notice that adding 'override' is not possible. I get the error 'Cannot override static method'.

Answer

In class B, the method list is a separate method from list in class A. They just share the same name, that's all.

The parameters of the two list methods are actually different:

// A.list
static func list(completion: (_ result:[A]?) -> Void) {
// B.list
static func list(completion: (_ result:[B]?) -> Void) {

A.list takes an argument of type (_ result: [A]?) -> Void while B.list takes a (_ result: [B]?) -> Void. The array type in the closure type's parameter list is different!

So you're not overridding anything, you're just overloading.

Note:

static methods can never be overridden! If you want to override a method, use class instead of static.

class A {
    class func get(completion: (_ result:A?) -> Void) {
        completion (nil)
    }
}


class B: A {
    override class func get(completion: (_ result:B?) -> Void) {
        completion (nil)
    }
}