Skip to content

Instantly share code, notes, and snippets.

@takasek
Created June 9, 2017 00:15
Show Gist options
  • Save takasek/28f31b7747ea81c94a69a042731814ac to your computer and use it in GitHub Desktop.
Save takasek/28f31b7747ea81c94a69a042731814ac to your computer and use it in GitHub Desktop.
さらに削ってみた #CodePiece
import Foundation
struct User: Codable {
struct Address: Codable {
let street: String
let city: String
let state: String
}
let name: String
let address: Address
let url: URL?
private enum UserCodingKeys: String, CodingKey {
case name
case url
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: UserCodingKeys.self)
name = try container.decode(String.self, forKey: .name)
address = try Address(from: decoder)
url = try container.decode(URL.self, forKey: .url)
}
}
let data = """
{
"name": "rizumita",
"street": "1-2-3 Foo",
"city": "Bar",
"state": "Baz",
"url": "http://yahoo.com"
}
""".data(using: .utf8)!
let decoder: JSONDecoder = JSONDecoder()
do {
let user: User = try decoder.decode(User.self, from: data)
print(user)
} catch {
print(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment