Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'.

like image 344
dce Avatar asked Nov 03 '16 11:11

dce


People also ask

Can I override static method in Swift?

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

Can you override a static method?

Can we override a static method? No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods.

What's the difference between a static variable and a class variable Swift?

Where static and class differ is how they support inheritance: When you make a static property it becomes owned by the class and cannot be changed by subclasses, whereas when you use class it may be overridden if needed.


2 Answers

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)
    }
}
like image 119
Sweeper Avatar answered Sep 18 '22 16:09

Sweeper


In short, as per rule, static methods can't be overridden.

like image 45
N a y y a r Avatar answered Sep 18 '22 16:09

N a y y a r