[英]Swift Protocol Function Overloading
是否可以重載協議功能並在直接處理協議類型時調用正確的定義?
這里有一些代碼來說明這個問題
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")
編輯:為了澄清,代碼工作。 我想知道為什么兩個調用都不使用特定於字符串的方法。
Double Edit:刪除了中間調度類以獲得更簡單的示例
這是錯誤,當前限制還是預期功能? 如果這是有意的,有人可以解釋一下原因嗎?
Swift 2.0,Xcode 7.0
回答
您不能重載協議函數並期望調用正確的定義。 這是因為在編譯時選擇要調用的定義。 由於編譯器不知道具體類型,因此它選擇編譯時已知的唯一定義doSomething<T>
。
我在http://swiftstub.com/上測試了你的代碼,它工作得很好。 首先它打印“我將使用特定方法”然后“通用方法”:
我將使用特定的方法泛型方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.