在处理协议类型时,是否可能重载协议函数并调用正确的定义?
以下是一些代码,用于说明此问题。
protocol SomeProtocol {
func doSomething<T>(obj: T)
}
class SomeClass : SomeProtocol {
func doSomething<T>(obj: T) {
print("Generic Method")
}
func doSomething(obj: String) {
print(obj)
}
}
let testClass = SomeClass()
testClass.doSomething("I will use the string specific method")
(testClass as SomeProtocol).doSomething("But I will use the generic method")
编辑:为澄清起见,代码是有效的。我想知道为什么两个调用都没有使用字符串特定方法。
双重编辑:删除了一个中间调度类作为更简单的示例
这是一个错误、当前限制还是预期功能?如果是有意的,请有人解释一下为什么?
Swift 2.0,Xcode 7.0
答案
您不能重载协议函数并期望调用正确的定义。这是因为在编译时选择要调用的定义。由于编译器不知道具体类型,因此它选择在编译时唯一已知的定义doSomething<T>
。