是否有一个标准的机制来注解Swift中的函数声明,以表明它们是存在的,因为一个类符合某些协议?
例如,这个声明可能是因为类符合NSCoding
而出现的。(用override
标记它会导致语法错误,所以这不是我想要的那种注释。)理想情况下,我正在寻找一个代码级注释(例如override
而不是/*! ... */
)。
// ... annotation such as "conform to NSCoding", if possible
func encodeWithCoder(encoder: NSCoder) {
// ...
}
您可以使用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:
注释:
class Foo: NSObject {
// ...
// MARK: NSCoding
required init(coder aDecoder: NSCoder) {
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
// ...
}
}