好吧,通过使用新的Decodable协议编写一些网络代码来修补Swift 4。以下错误导致多个编译器错误:
// A lot has been stripped out of this for brevity, so we can focus on this specific constant
struct APIRequest {
let decoder = JSONDecoder()
let decodableType: <T.Type where T : Decodable> // Compiler errors here
// This function compiles and runs successfully when I pass it in explicitly (by removing the above constant)
func decodeJsonData<T>(_ data: Data, for type: T.Type) throws -> T where T : Decodable {
return try decoder.decode(type, from: data)
}
}
decodableType应该是&#39; Type&#39;任何符合可解码协议的结构/类(即用户符合可解码或可编码的User.self)。我如何告诉编译器?
编辑:换句话说,我想写这样的代码......
struct APIRequest {
let decoder = JSONDecoder()
let decodableType: <T.Type where T : Decodable> // Not sure how to declare this type
func decodeJsonData(_ data: Data,) throws -> Decodable {
return try decoder.decode(decodableType, from: data)
}
}
这意味着保持struct的常量内的第一个代码块中的泛型参数。我只是不知道如何在Swift中正确地写出类型。
答案 0 :(得分:2)
如果您希望您的结构具有泛型类型,则必须将其声明为此类,而不是与您尝试的内容一样的成员:
struct APIRequest<T: Decodable> {
let decoder = JSONDecoder()
func decodeJSONData(from data: Data) throws -> T {
return try decoder.decode(T.self, from: data)
}
}
或者您可以将泛型类型限制为函数的范围:
struct APIRequest {
let decoder = JSONDecoder()
func decode<T: Decodable>(from data: Data) throws -> T {
return try decoder.decode(T.self, from: data)
}
}