我正在使用Decodable
Swift 4 中引入的新协议。在我的单元测试中,我想使用一个通用方法来解码特定Decodable
类型的特定 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)")
}
}
编译器给我以下错误:
In argument type 'Obj.Type', 'Obj' does not conform to expected type 'Decodable'
Obj
由于该where
子句,我会想象这是可解码的。
该功能有什么问题?