LoginSignup
1
2

More than 3 years have passed since last update.

APIKitをCodableで使用する

Posted at

https://github.com/ishkawa/APIKit ではJSONDataParserが提供されていますが、実装を見るとこのParserで返されるのはJSONをSwiftの世界の型に変換したものです。 (Dictionary, Array, String, etc...)

    public func parse(data: Data) throws -> Any {
        guard data.count > 0 else {
            return [:]
        }

        return try JSONSerialization.jsonObject(with: data, options: readingOptions)
    }

JSONDataParserより抜粋

Codableに準拠した独自の型に変換するためには JSONDecoder().decode(Decodable.Protocol, from: Data)
を使用しますが、そのためにはData型を渡す必要があります。
なので、JSONDataParserは使用できず、そのままのDataを返す空のDataParserが必要です。

struct NopeDataParser: DataParser {
    var contentType: String?

    func parse(data: Data) throws -> Any {
        data
    }
}

これを用いると、以下のメソッドで取得できるobjectの型はDataになり、Codableに準拠した型に変換することができます。

    func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
        guard let data = object as? Data else { throw DomainError.parseFailed(object) }
        return try JSONDecoder().decode(Response.self, from: data)
    }
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2