带Swift 4的可解码泛型
我正在使用Swift 4中引入的新带Swift 4的可解码泛型,swift,generics,swift4,decodable,Swift,Generics,Swift4,Decodable,我正在使用Swift 4中引入的新可解码协议。 在我的单元测试中,我想使用一种通用方法,对特定的可解码类型的特定JSON文件进行解码 我编写了以下与JSONDecoderdecode方法匹配的函数: var jsonDecoder: JSONDecoder = { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 return decoder }()
可解码
协议。
在我的单元测试中,我想使用一种通用方法,对特定的可解码类型的特定JSON文件进行解码
我编写了以下与JSONDecoder
decode
方法匹配的函数:
var jsonDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}()
static let bundle: Bundle = {
let testBundle = Bundle(for: Decodable.self)
let sampleURL = testBundle.url(forResource: "api_samples", withExtension: "bundle")!
return Bundle(url: sampleURL)!
}()
static func getJSONSample(fileName: String) throws -> Data {
let url = Decodable.bundle.url(forResource: fileName, withExtension: "json")!
return try Data(contentsOf: url)
}
func assertDecode<Obj>(_ type: Obj.Type, fileName: String) where Obj: Decodable {
do {
let data = try Decodable.getJSONSample(fileName: fileName)
let _ = try jsonDecoder.decode(type, from: data)
// Same by using Obj.self, Obj.Type
} catch let error {
XCTFail("Should not have failed for \(type) with json \(fileName): \(error)")
}
}
var-jsonDecoder:jsonDecoder={
let decoder=JSONDecoder()
decoder.dateDecodingStrategy=.iso8601
返回解码器
}()
静态let包:包={
让testBundle=Bundle(for:Decodable.self)
让sampleURL=testBundle.url(用于资源:“api_样本”,扩展名为:“bundle”)!
返回捆绑包(url:sampleURL)!
}()
静态func getJSONSample(文件名:String)抛出->数据{
让url=Decodable.bundle.url(forResource:fileName,扩展名为:“json”)!
返回try数据(contentsOf:url)
}
func assertDecode(uType:Obj.type,文件名:String),其中Obj:Decodable{
做{
让data=try Decodable.getJSONSample(文件名:fileName)
让我们试试jsonDecoder.decode(类型,from:data)
//使用Obj.self和Obj.Type时相同
}捕捉错误{
XCTFail(“对于使用json\(文件名):\(错误)的\(类型)不应失败”)
}
}
编译器给了我以下错误:
参数类型“Obj.type”中的“Obj”不符合预期的类型“Decodable”
我可以想象,Obj
由于where
子句是可解码的
该函数有什么问题?与其使用“where”语句,不如通过限制泛型本身使您的生活更轻松:
func assertDecode<Obj: Decodable>(_ type: Obj.Type, fileName: String)
func assertDecode(uu类型:Obj.type,文件名:String)
如何声明可解码的.getJSONSample(文件名:)
?像这样静态函数getJSONSample(文件名:String)抛出->数据
在哪里写?无法在我的Xcode 9 beta 2中编译部分Decodable.getJSONSample(fileName:fileName)
。您在哪里编写代码还不够清楚,但很可能您有另一种Decodable
类型。编译器将Decodable
作为您的代码,即使它是在where
子句中编写的。中的Decodable
,其中Obj:Decodable
是您的Decodable
,而不是Swift标准库的Decodable
。您是对的,我在项目中有两个Decodable
类