1

我正在使用DecodableSwift 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子句,我会想象这是可解码的。

该功能有什么问题?

4

1 回答 1

2

与其做一个“where”语句,不如通过限制泛型本身让你的生活更轻松:

func assertDecode<Obj: Decodable>(_ type: Obj.Type, fileName: String)
于 2018-04-15T18:26:44.557 回答