我正在尝试编写一个通用函数来解析几种不同的数据类型。
最初这个方法只适用于 Codable 类型,所以它的泛型类型被约束,<T: Codable>一切都很好。不过现在,我正在尝试扩展它以检查返回类型是否为 Codable,并根据该检查相应地解析数据
func parse<T>(from data: Data) throws -> T? {
switch T.self {
case is Codable:
// convince the compiler that T is Codable
return try? JSONDecoder().decode(T.self, from: data)
case is [String: Any].Type:
return try JSONSerialization.jsonObject(with: data, options: []) as? T
default:
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
所以,你可以看到类型检查工作正常,但我被困在得到JSONDecoder().decode(:)接受T的Codable类型,一旦我检查了,这是。上面的代码不能编译,有错误
Cannot convert value of type 'T' (generic parameter of instance method 'parse(from:)') to expected argument type 'T' (generic parameter …