Swift重写静态方法编译错误

dce*_*dce 9 static compiler-errors compilation swift

我有这两个快速的课程:

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)
    }        
}
Run Code Online (Sandbox Code Playgroud)

尝试编译这会引发错误"覆盖声明需要'覆盖'关键字",但仅适用于B类的'get'方法.'list'方法编译良好.[B]有什么区别?和B?对于这种情况下的编译器?

编辑:另请注意,无法添加"覆盖".我收到错误'无法覆盖静态方法'.

Swe*_*per 24

B,该方法list是从一个单独的方法list中类A.他们只是拥有相同的名字,就是这样.

这两种list方法的参数实际上是不同的:

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

A.list采取类型的参数,(_ result: [A]?) -> VoidB.list采取(_ result: [B]?) -> Void.闭包类型参数列表中的数组类型是不同的!

所以你没有覆盖任何东西,你只是超载.

注意:

static方法永远不会被覆盖!如果要覆盖方法,请使用class而不是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)
    }
}
Run Code Online (Sandbox Code Playgroud)