声明一个符合协议的泛型常量

Declaring a constant of generic type that conforms to protocol

好的,通过使用新的 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 应该是符合 Decodable 协议的任何 struct/class 的 'Type'(即 User.self,其中 User 符合 decodable 或 codable)。我如何告诉编译器这个?

编辑:换句话说,我想这样写代码...

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

这意味着将第一个代码块中的泛型参数保存在结构常量中。我只是不知道如何在 Swift.

中正确写出类型

如果您希望您的结构具有泛型类型,则必须将其声明为泛型类型,而不是像您尝试的那样声明为成员:

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