【发布时间】:2022-01-21 18:41:51
【问题描述】:
我想做一个辅助函数,它接受可编码/可解码类型的输入,以便对 json 进行编码或解码。我试过了
static func loadCache<T:Decodable>(fileName:String, type:T)throws->T{
let data = try FileManager.loadCache(fileName: fileName)
return try JSONDecoder().decode(T.self, from: data)
}
使用函数
let products = try loadCache(fileName: Product.cacheFileName(), type: [Product])
我收到错误Type '[Product].Type' cannot conform to 'Decodable'
将 this 传递给函数的正确方法是什么 谢谢
【问题讨论】:
-
你可以使用 T.type 和 [Product].self 但你不能使用这样的文件
-
你可以使用这样的文件:- stackoverflow.com/questions/24410881/…
-
@NoorAhmedNatali FileManager.loadCache 是我自己的生成数据的自定义扩展。我应该在我猜的问题中提到这一点