【发布时间】:2018-01-22 02:55:26
【问题描述】:
在 Swift 中,您不能在协议定义本身中定义函数或属性的默认实现,即:
protocol Container {
//These are fine
associatedtype Item
mutating func append(_ item: Item)
var count: Int { get set }
subscript(i: Int) -> Item { get }
//These are not fine
var defaultValue: Int = 10
mutating func messWithCount(){
self.count *= 10
}
}
extension Container {
//This is fine though
mutating func messWithCount(){
self.count *= 10
}
}
但是您可以通过扩展来做到这一点(虽然扩展不支持存储属性,但它们支持函数和计算的 - 尽管存储属性问题可能是 worked around)。
这背后的解释是什么?作为补充,optional func 只有在我们将 Protocol 和 func 都标记为 @objc 并因此使其无法用于 Structs/Enums(基于 Value 而非 Reference)时才能实现的解释是什么?
编辑:在扩展示例中添加
【问题讨论】:
-
协议声明中的默认实现是不可能的,这并没有真正的原因;区别只是语法上的。因此,我认为实施(如果有的话)不会是一个高优先级。不过它是included in the generics manifesto,因此可能会考虑用于该语言的更高版本。
标签: swift reference protocols extension-methods