可解码通用Swift 4

时间:2017-07-03 17:09:04

标签: swift generics swift4 decodable

我正在使用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子句而可解码。

该功能有什么问题?

1 个答案:

答案 0 :(得分:2)

不是通过“where”语句,而是通过限制泛型本身来使您的生活更轻松:

func assertDecode<Obj: Decodable>(_ type: Obj.Type, fileName: String)