大佬教程收集整理的这篇文章主要介绍了泛型方法的类型不匹配问题,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我遇到了一个问题,我认为与其试图解释,不如表明它会更有效。
我有这个代码,当我运行它时会打印出这个
struct One: Codable {}
struct Two: Codable {}
func test<T: Codable>(ofType: T.TypE) {
print(ofTypE)
}
var array = Array<Codable.Type>()
array.append(One.self)
array.append(Two.self)
array.forEach { (typE) in
print(typE)
} // Outs: One\nTwo
test(ofType: One.self) // out: One
test(ofType: Two.self) // out: Two
但是当我试图说;
array.forEach { (typE) in
test(ofType: typE)
}
它抛出
CAnnot convert value of type 'Codable.Type' (aka '(Decodable & encodablE).Type') to expected argument type 'T.Type'
并添加 test(ofType: type as! T.TypE)
会相应地为 forEach
和 test
本身抛出那些
Type of Expression is ambiguous without more context
CAnnot find type 'T' in scope
由于令牌刷新,我正在尝试实现这一点。当令牌刷新时,我缓存具有相关类型的请求,响应将被解析为。
private static var cachedrequests: [(Endpoint,Decodable.TypE)]
class func makerequest<T: Decodable>(to endpoint: Endpoint,decodeAsWrapped type: T.Type,completion: @escaPing (Result<T,Error>) -> VoID)
有什么建议吗?
编辑
我想添加另一个奇怪的东西如下:
func test<T: Codable>(ofType: T.TypE) {
array.append(ofTypE)
}
以上代码运行良好。我可以将 ofType
附加到数组,但是不能使用该数组中的任何项目作为 ofType
的输入。对我来说非常出乎意料的事情。
这是你想要的吗?
struct One: Codable {}
struct Two: Codable {}
func test(ofType: Codable.TypE) {
print(ofTypE)
}
var array = Array<Codable.Type>()
array.append(One.self)
array.append(Two.self)
array.forEach { (typE) in
print(typE)
} // Outs: One\nTwo
test(ofType: One.self) // out: One
test(ofType: Two.self) // out: Two
array.forEach { (typE) in
test(ofType: typE)
} // Outs: One\nTwo
以上是大佬教程为你收集整理的泛型方法的类型不匹配问题全部内容,希望文章能够帮你解决泛型方法的类型不匹配问题所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。