Swift泛型错误:无法转换类型'Type< T>'的值到期望的参数类型“类型< _>” [英] Swift generics error: Cannot convert value of type 'Type<T>' to expected argument type 'Type<_>'

查看:298
本文介绍了Swift泛型错误:无法转换类型'Type< T>'的值到期望的参数类型“类型< _>”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个设置:

 协议MyProcotol {
}

class MyModel :MyProcotol {
}

enum结果< T> {
case success(value:T)
case failure
}

class Test {
func test< T:MyProcotol>(result& ; T>) - > Void){
let model = MyModel()
let result = Result.success(value:model)
completion(result)
}



$ b为什么我不能调用完成(结果) code>?我收到此错误:

无法将类型'Result'的值转换为期望的参数类型'Result< _>'



任何解决方法?

解决方案

您正在使用非通用混凝土类型 MyModel 在一个泛型函数中,这是行不通的。



你可以这样做

  class Test {
func test< T:MyProcotol>(item:T,completion:(Result< T>) - & ){
让结果:结果< T> = .success(value:item)
completion(result)
}
}


Please consider this setup:

protocol MyProcotol {
}

class MyModel: MyProcotol {
}

enum Result<T> {
    case success(value: T)
    case failure
}

class Test {
    func test<T: MyProcotol>(completion: (Result<T>) -> Void) {
        let model = MyModel()
        let result = Result.success(value: model)
        completion(result)
    }
}

Why can't I call completion(result)? I'm getting this error:

Cannot convert value of type 'Result' to expected argument type 'Result<_>'

Any workaround?

解决方案

You are using a non-generic concrete type MyModel in a generic function, that doesn't work.

You could do something like this

class Test {
    func test<T: MyProcotol>(item: T, completion: (Result<T>) -> Void) {
        let result : Result<T> = .success(value: item)
        completion(result)
    }
}

这篇关于Swift泛型错误:无法转换类型'Type&lt; T&gt;'的值到期望的参数类型“类型&lt; _&gt;”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆