是否有可能重載協議函數並在直接處理協議類型時調用正確的定義?Swift協議功能重載
下面是一些代碼來說明問題
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")
編輯:爲了澄清,代碼工作。我想知道爲什麼這兩個調用不使用特定於字符串的方法。
雙編輯:刪除一個簡單的例子
這是一個錯誤,電流限制,或預期的功能中介派遣類?如果這是有意的,有人可以解釋爲什麼嗎?
雨燕2.0的Xcode 7.0
回答
不能超載協議功能,並期望正確的定義被調用。這是因爲要調用的定義是在編譯時挑選的。由於編譯器不知道具體類型,因此它選擇編譯時已知的唯一定義,即doSomething<T>
。
我在操場RUND這個代碼,它工作得很好:*我會用具體方法\ n一般方法* – vikingosegundo
該代碼有效。我很困惑爲什麼這兩個調用不使用特定的方法。 – eunoia
這兩種方法都使用 – vikingosegundo