为什么我的 CustomType 无法符合 Decodable,即使我符合它?

use*_*ser 3 swift

我有一个符合 Decodable 的 CustomType,当我想将它用作我的函数所需的值时,Xcode 抱怨 CustomType 不符合 Decodable!我应该明确地使 CustomType 构造发生,我也这样做了,但它没有解决问题!我在这里缺少什么?

错误:

类型“CustomType.Type”不能符合“Decodable”

let stringOfJSON: String = """
{ "name": "SwiftPunk", "age": 35 }
"""

let dataOfJSON: Data? = stringOfJSON.data(using: String.Encoding.utf8)
Run Code Online (Sandbox Code Playgroud)
struct CustomType: Decodable {
    
    enum Codingkeys: String, CodingKey {
        case name, age
    }
    
    var name: String
    var age: Int
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Codingkeys.self)
        name = try container.decode(String.self, forKey: .name)
        age = try container.decode(Int.self, forKey: .age)
    }
    
    
}
Run Code Online (Sandbox Code Playgroud)
func decoderFunction<T: Decodable>(dataOfJSON: Data?, customType: T, decodedValue: (T) -> Void) {
    
    if let unwrappedDataOfJSON: Data = dataOfJSON {
        
        let dataJSONDecoder: JSONDecoder = JSONDecoder()
        
        do {
            let value: T = try dataJSONDecoder.decode(T.self, from: unwrappedDataOfJSON)
            decodedValue(value)
        } catch {
            print("The Data could not be decoded!")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用例:

decoderFunction(dataOfJSON: dataOfJSON, customType: CustomType.self, decodedValue: { value in
 
})
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 8

参数类型customType不正确。它应该是( )的元类型,而不是。TT.TypeT

func decoderFunction<T: Decodable>(dataOfJSON: Data?, customType: T.Type, decodedValue: (T) -> Void) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

该方法需要一个 type 的值T,该值应该符合Decodable,但是您给它一个 type 的值CustomType.Type,该值不符合Decodable(但请注意,确实CustomType如此)。

customType另请注意,您根本不需要该参数。T如果您在闭包中指定类型,则可以推断:

func decoderFunction<T: Decodable>(dataOfJSON: Data?, decodedValue: (T) -> Void) {
    ...
}

decoderFunction(dataOfJSON: dataOfJSON, decodedValue: { (value: CustomType) in
 
})
Run Code Online (Sandbox Code Playgroud)