[英]Value of Protocol type 'name' cannot conform to protocol 'name' with generic function
我有一個帶有通用參數的 function,當它被調用時,我收到錯誤Value of protocol type 'AddableObject' cannot conform to 'AddableObject'; only struct/enum/class types can conform to protocols
Value of protocol type 'AddableObject' cannot conform to 'AddableObject'; only struct/enum/class types can conform to protocols
我有以下 class 和協議
class DataManager{
func updateItem<Item: AddableObject>(itemToUpdate: Item, updateValues: [String : Any], completion: @escaping ((Result<Item, Error>) -> ())){ }
}
protocol AddableObject{ }
這是我的VC中的代碼
class vc: UIViewController{
weak var task: Task?
viewDidLoad(){
super.viewDidLoad()
}
private func uploadTask(){
guard let taskToUpdate = self.task else{return}
//this is where I get the error
DataManager.shared.updateItem(itemToUpdate: taskToUpdate, updateValues: ["index": 1]){result in
}
}
}
這是我的任務 object
class Task: AddableObject{
}
當我嘗試從我的 VC 調用updateItem
方法時,出現錯誤
Value of protocol type 'AddableObject' cannot conform to 'AddableObject'; only struct/enum/class types can conform to protocols
為什么我會收到此錯誤?
一個明顯的問題:您的聲明weak var task: Task?
聲明一個可選的。 但是參數itemToUpdate:
不是可選的。 它是符合 AddableObject 的泛型類型,而 Optional不是符合 AddableObject 的東西。
如果我們對此進行糾正,以及您顯示的代碼中的其他明顯問題,則生成的代碼可以完美編譯:
class DataManager{
func updateItem<Item: AddableObject>(itemToUpdate: Item, updateValues: [String : Any], completion: @escaping ((Result<Item, Error>) -> ())){ }
}
protocol AddableObject{ }
class vc: UIViewController{
weak var task: Task?
private func uploadTask(){
guard let taskToUpdate = self.task else {return}
DataManager().updateItem(itemToUpdate: taskToUpdate, updateValues: ["index": 1]){result in
}
}
}
class Task: AddableObject{
}
因此,我必須得出結論,問題出在您沒有向我們展示的代碼中,或者您向我們歪曲了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.