Skip to content

Instantly share code, notes, and snippets.

@takasek
Last active June 21, 2017 07:53
Show Gist options
  • Save takasek/d4ab003f989244106ce3dafd5ed5f914 to your computer and use it in GitHub Desktop.
Save takasek/d4ab003f989244106ce3dafd5ed5f914 to your computer and use it in GitHub Desktop.
別のCodingKeysを用意して、複数キーを使ってプロパティを組み立てる例 #CodePiece
import UIKit
func decodeJSON<T: Decodable>(_ t: T.Type, from string: String) {
let data = string.data(using: .utf8)!
let decoder = JSONDecoder()
let s = try! decoder.decode(t, from: data)
print(s)
}
struct KeyedWithComposed: Decodable {
enum Kind {
case image(UIImage)
case url(URL)
case text(String)
}
let id: Int
let kind: Kind
private enum CodingKeys: CodingKey {
case id
case kind
}
private enum KindCodingKeys: CodingKey {
case kind
case image
case url
case text
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
kind = try type(of: self).makeKind(from: decoder)
}
private static func makeKind(from decoder: Decoder) throws -> Kind {
let composingContainer = try decoder.container(keyedBy: KindCodingKeys.self)
switch try composingContainer.decode(String.self, forKey: .kind) {
case "image":
let imageData = try composingContainer.decode(Data.self, forKey: .image)
guard let image = UIImage(data: imageData) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [KindCodingKeys.image],
debugDescription: "imageのデータがおかしい"))
}
return .image(image)
case "url":
return .url(try composingContainer.decode(URL.self, forKey: .url))
case "text":
return .text(try composingContainer.decode(String.self, forKey: .text))
case _:
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [CodingKeys.kind],
debugDescription: "kindの値が想定外"))
}
}
}
decodeJSON(KeyedWithComposed.self, from: """
{
"id": 100,
"kind": "text",
"image": null,
"url": null,
"text": "imageやurlはないけどtextはあるよ"
}
""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment