gpt4 book ai didi

Swift 泛型错误 : Cannot convert value of type 'Type' to expected argument type 'Type<_>'

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:27 35 4
gpt4 key购买 nike

请考虑以下设置:

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

为什么我不能调用completion(result)?我收到此错误:

无法将“Result”类型的值转换为预期的参数类型“Result<_>”

任何解决方法?

最佳答案

您在泛型函数中使用了非泛型具体类型 MyModel,这是行不通的。

你可以这样做

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

关于Swift 泛型错误 : Cannot convert value of type 'Type<T>' to expected argument type 'Type<_>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44018923/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com