注释支持符合协议的Swift函数声明?

时间:2015-08-20 07:25:25

标签: swift protocols swift2 swift-protocols

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

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

/*! ... */

1 个答案:

答案 0 :(得分:3)

您可以使用extension。例如:

protocol SomeProtocol {
    func doIt() -> Int
}


class ConcreteClass {
    ....
}

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

但您无法在required中定义extension初始值设定项,例如:

// 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) {
        // ... 
    }
}