-
Notifications
You must be signed in to change notification settings - Fork 5
/
Person.swift
53 lines (37 loc) · 1.35 KB
/
Person.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// Person.swift
// Codable
//
// Created by Nate Walczak on 10/5/18.
// Copyright © 2018 Detroit Labs. All rights reserved.
//
import Foundation
class Person: Codable {
var age: Int?
var first: String?
var last: String?
init() {
}
enum CodingKeys: CodingKey {
case age
case name
}
enum NameCodingKeys: CodingKey {
case first
case last
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.age = try container.decodeIfPresent(Int.self, forKey: .age)
let nameContainer = try container.nestedContainer(keyedBy: NameCodingKeys.self, forKey: .name)
self.first = try nameContainer.decodeIfPresent(String.self, forKey: .first)
self.last = try nameContainer.decodeIfPresent(String.self, forKey: .last)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(age, forKey: .age)
var nameContainer = container.nestedContainer(keyedBy: NameCodingKeys.self, forKey: .name)
try nameContainer.encodeIfPresent(first, forKey: .first)
try nameContainer.encodeIfPresent(last, forKey: .last)
}
}