Swift 4 で導入された新しいDecodable
プロトコルを使用しています。単体テスト内で、特定の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
その機能の何が問題になっていますか?