简体   繁体   English

协议类型“名称”的值不能符合具有通用 function 的协议“名称”

[英]Value of Protocol type 'name' cannot conform to protocol 'name' with generic function

I have a function with generic parameters and when it is called I get the error Value of protocol type 'AddableObject' cannot conform to 'AddableObject'; only struct/enum/class types can conform to protocols我有一个带有通用参数的 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

I have the following class and protocols我有以下 class 和协议

class DataManager{

      func updateItem<Item: AddableObject>(itemToUpdate: Item, updateValues: [String : Any], completion: @escaping ((Result<Item, Error>) -> ())){ }

}
protocol AddableObject{ }

This is the code in my VC这是我的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 

      }

  }

}

This is my task object这是我的任务 object

class Task: AddableObject{

}

When I try to call the updateItem method from my VC I get the error当我尝试从我的 VC 调用updateItem方法时,出现错误

Value of protocol type 'AddableObject' cannot conform to 'AddableObject'; only struct/enum/class types can conform to protocols

Why am I getting this error?为什么我会收到此错误?

One obvious issue: your declaration weak var task: Task?一个明显的问题:您的声明weak var task: Task? declares an Optional.声明一个可选的。 But the parameter itemToUpdate: is not an Optional.但是参数itemToUpdate:不是可选的。 It is a generic type that conforms to AddableObject — and an Optional is not something that conforms to AddableObject.它是符合 AddableObject 的泛型类型,而 Optional不是符合 AddableObject 的东西。


If we correct for that, and for the other obvious issues in the code you have shown, the resulting code compiles perfectly:如果我们对此进行纠正,以及您显示的代码中的其他明显问题,则生成的代码可以完美编译:

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{
}

Thus I have to conclude that the trouble is in code you have not shown us, or that you have misrepresented to us.因此,我必须得出结论,问题出在您没有向我们展示的代码中,或者您向我们歪曲了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM