如何使用协议关联类型在Swift中编写泛型函数

如何使用协议关联类型在Swift中编写泛型函数,swift,generics,Swift,Generics,我正在尝试编写通用处理函数,该函数将接收ResourceModel实例并以某种方式处理它们: func handleGeneric<R, M: ResourceModel>(resource: R, modelType: M.Type) { 但我明白了 Cannot convert value of type 'ResourceA' to expected argument type '_.R' 不要把R写在签名上,用M.R写在你的签名上 func handleGeneric&l

我正在尝试编写通用处理函数,该函数将接收ResourceModel实例并以某种方式处理它们:

func handleGeneric<R, M: ResourceModel>(resource: R, modelType: M.Type) {
但我明白了

Cannot convert value of type 'ResourceA' to expected argument type '_.R'
不要把R写在签名上,用M.R写在你的签名上

func handleGeneric<M: ResourceModel>(resource: M.R, modelType: M.Type) {

卢的回答是正确的。你只是说得不对。您需要ModelA.self,而不是ModelA.Type。
handleGeneric<ResourceA, ModelA>(ResourceA(id: 1, name: "A"))
handleGeneric<ResourceB, ModelB>(ResourceB(id: 2, number: 10))
handleGeneric<ResourceC, ModelC>(ResourceC(id: 3, "foo": "bar"))
handleGeneric<ResourceD, ModelD>(ResourceD(id: 4, "egg": "spam"))
handleGeneric(resource: ResourceA(id: 1, name: "A"), modelType: ModelA.Type)
handleGeneric(resource: ResourceB(id: 2, number: 10), modelType: ModelB.Type)
Cannot convert value of type 'ResourceA' to expected argument type '_.R'
func handleGeneric<M: ResourceModel>(resource: M.R, modelType: M.Type) {