【问题标题】:Is it possible to have a Swift protocol that enforces static method and not class method or vice versa?是否有可能有一个强制静态方法而不是类方法的 Swift 协议,反之亦然?
【发布时间】:2017-02-10 20:39:22
【问题描述】:

是否有可能有一个 Swift 协议强制执行静态方法而不是类方法,反之亦然?

例如,即使协议设置为类协议,也不允许使用 class func 或 final class func:

protocol MyProtocol: class {
    final class func dummyClassMethod()
}

或者在这种情况下,允许一个类创建一个静态方法或符合这个的类方法:

protocol MyProtocol: class {
    static func dummyClassMethod()
}

【问题讨论】:

    标签: swift3 protocols


    【解决方案1】:

    您不能,因为苹果的文档明确表示为此目的仅使用 static

    协议中声明classstatic 方法要求 声明,static声明标记方法声明 修饰符

    来源:Protocol Method Declaration


    当您在class 中实现protocolstatic 方法时,在您的实现中使用classstatic 没有区别。

    protocol ProtocolForClasses: class {
      static func method()
    }
    
    class ClassOne: ProtocolForClasses {
      class func method() {
    
      }
    }
    
    class ClassTwo: ProtocolForClasses {
      static func method() {
    
      }
    }
    

    【讨论】:

    • "在你的实现中使用 classstatic 没有区别" → 实际上是有区别的,static 方法不能在子类中被覆盖,而 class 方法可以。
    猜你喜欢
    • 2012-01-06
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2016-06-26
    • 1970-01-01
    相关资源
    最近更新 更多