【问题标题】:Swift override static method compile errorSwift覆盖静态方法编译错误
【发布时间】:2017-03-16 23:40:41
【问题描述】:

我有这两个 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)
    }        
}

试图编译这个会引发错误“覆盖声明需要一个'override'关键字”但仅适用于B类的'get'方法。'list'方法编译得很好。 [B] 和有什么不一样?和乙?对于这种情况下的编译器?

编辑:还要注意添加“覆盖”是不可能的。我收到错误“无法覆盖静态方法”。

【问题讨论】:

    标签: swift static compilation compiler-errors


    【解决方案1】:

    在类B 中,方法list 是与类A 中的list 分开的方法。他们只是同名而已。

    list这两个方法的参数其实是不一样的:

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

    A.list 采用 (_ result: [A]?) -> Void 类型的参数,而 B.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)
        }
    }
    

    【讨论】:

    • 谢谢@Sweeper。为什么'get'方法的情况不一样? B.get 需要一个类型 B 的参数?和 A.get 类型 A?
    • 哦,我忘了解释!嗯,基本上就是“这个方法是否覆盖另一个方法”算法是如何实现的。算法只是认为数组是不兼容的类型,而子类和超类是兼容的类型@dce
    【解决方案2】:

    简而言之,根据规则,static methods 不能被覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多