Created
June 9, 2017 00:15
-
-
Save takasek/28f31b7747ea81c94a69a042731814ac to your computer and use it in GitHub Desktop.
さらに削ってみた #CodePiece
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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