给定这两个协议(protocol)及其扩展:
protocol FirstDelegate {
func someFunc()
}
protocol SecondDelegate {
func someFunc()
}
extension FirstDelegate {
func someFunc() {
print("First delegate")
}
}
extension SecondDelegate {
func someFunc() {
print("Second delegate")
}
}
并试图同时符合它们:
class SomeClass: FirstDelegate, SecondDelegate {}
我收到编译时错误:
Type 'SomeClass' does not conform to protocol 'FirstDelegate'
交换 FirstDelegate
和 SecondDelegate
:
class SomeClass: SecondDelegate, FirstDelegate {}
产生反向:
Type 'SomeClass' does not conform to protocol 'SecondDelegate'
删除其中一个扩展可以解决问题。同样在 SomeClass
中为 someFunc()
提供实现。
这个协议(protocol)扩展功能对我来说是相当新的。此外,Apple 官方“Swift 编程指南(预发行版)”中关于它的信息目前很少。
我在这里是否违反了一些协议(protocol)扩展规则?
最佳答案
一个协议(protocol)定义了一个要求(方法,属性,...) 一致性类型。
protocol FirstDelegate {
func someFunc()
}
protocol SecondDelegate {
func someFunc()
}
使用相同的必需方法 someFunc()
定义两个协议(protocol)。
一致性类型必须实现此方法:
class SomeClass: FirstDelegate, SecondDelegate {
func someFunc() {
print("SomeClass implementation")
}
}
协议(protocol)扩展 提供方法和属性实现 符合类型。协议(protocol)扩展的一个特例是 默认实现,这是您在此处定义的:
extension FirstDelegate {
func someFunc() {
print("First delegate")
}
}
它为所有类型定义了 someFunc()
的默认实现
符合 FirstDelegate
。因为这是唯一需要的
该协议(protocol)的方法,一个符合标准的类不需要定义
方法:
class SomeClass: FirstDelegate {
}
SomeClass().someFunc() // Output: First delegate
但是如果类提供了自己的实现,那么 将被使用:
class SomeClass: FirstDelegate {
func someFunc() {
print("SomeClass implementation")
}
}
SomeClass().someFunc() // Output: SomeClass implementation
在你的例子中,你已经定义了 someFunc()
的默认实现
对于两种协议(protocol):
extension FirstDelegate {
func someFunc() {
print("First delegate")
}
}
extension SecondDelegate {
func someFunc() {
print("Second delegate")
}
}
如果一个类提供了自己的协议(protocol),它仍然可以符合这两种协议(protocol) 所需方法的实现:
class SomeClass: FirstDelegate, SecondDelegate {
func someFunc() {
print("SomeClass implementation")
}
}
但是类不能通过使用默认实现来符合
class SomeClass: FirstDelegate, SecondDelegate {
}
对于两种协议(protocol) 因为有冲突。未指定默认值 应该使用实现,这就是编译器提示的原因。
实际上这个类现在没有符合协议(protocol)。 这可以在报告导航器的完整编译器日志中看到:
main.swift:24:7: error: type 'SomeClass' does not conform to protocol 'FirstDelegate' class SomeClass: FirstDelegate, SecondDelegate { ^ main.swift:5:10: note: multiple matching functions named 'someFunc()' with type '() -> ()' func someFunc() ^ main.swift:19:10: note: candidate exactly matches func someFunc() { ^ main.swift:13:10: note: candidate exactly matches func someFunc() { ^ main.swift:24:7: error: type 'SomeClass' does not conform to protocol 'SecondDelegate' class SomeClass: FirstDelegate, SecondDelegate { ^ main.swift:9:10: note: multiple matching functions named 'someFunc()' with type '() -> ()' func someFunc() ^ main.swift:19:10: note: candidate exactly matches func someFunc() { ^ main.swift:13:10: note: candidate exactly matches func someFunc() { ^
关于 swift 2.0 : Protocol extensions: Two protocols with the same function signature compile error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31884741/