【问题标题】:Annotating Swift function declarations that support conformance to a protocol?注释支持协议一致性的 Swift 函数声明?
【发布时间】:2015-11-13 17:25:42
【问题描述】:

在 Swift 中是否有一种标准机制来注释函数声明以表明它们存在是因为类符合某些协议?

例如,此声明可能存在,因为类符合NSCoding。 (用override 标记它会导致语法错误,所以它不是我正在寻找的那种注释。)理想情况下,我正在寻找代码级注释(例如override 而不是/*! ... */)。

// ... annotation such as "conform to NSCoding", if possible
func encodeWithCoder(encoder: NSCoder) {
   // ...
}

【问题讨论】:

  • 在评论或代码中注释?
  • @Aderstedt 在代码中注释是最好的(参见 Q 的更新)。
  • AFAIK 无法在代码中注释协议一致性。使用 cmets。
  • @robertvojta 太糟糕了。 (我现在正在使用 cmets,但希望有一个替代方案。)

标签: swift protocols swift2 swift-protocols


【解决方案1】:

您可以使用extension。例如:

protocol SomeProtocol {
    func doIt() -> Int
}


class ConcreteClass {
    ....
}

extension ConcreteClass: SomeProtocol {
    func doIt() -> Int {
       // ...
       return 1
    }
}

但是你不能在extension中定义required初始化器,例如:

// THIS DOES NOT WORK!!!

class Foo: NSObject {
}
extension Foo: NSCoding {
    required convenience init(coder aDecoder: NSCoder) {
        self.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // ...
    }
}

发出错误:

error: 'required' initializer must be declared directly in class 'Foo' (not in an extension)
    required convenience init(coder aDecoder: NSCoder) {
    ~~~~~~~~             ^

在这种情况下,您应该使用// MARK: comments

class Foo: NSObject {

    // ...


    // MARK: NSCoding

    required init(coder aDecoder: NSCoder) {
        super.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // ... 
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多