-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCodable_vs_SuperCoable.swift
68 lines (52 loc) · 1.48 KB
/
Codable_vs_SuperCoable.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//
/*
* Created by 游宗諭 in 2021/4/10
*
* Using Swift 5.0
*
* Running on macOS 11.2
*/
import Foundation
// MARK: - StudentWithCodable
struct StudentWithCodable: Codable {
// MARK: Lifecycle
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.aName = try container.decode(String.self, forKey: .aName)
let gradeDecoded = try container.decode(Double.self, forKey: .grade)
self.grade = Int(gradeDecoded)
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case id = "id"
case aName = "name"
case grade = "grade"
}
var id: String
var aName: String
var grade: Int
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(aName, forKey: .aName)
try container.encode(Double(grade), forKey: .grade)
}
}
// MARK: - StudentWithSuperCodable
struct StudentWithSuperCodable: SuperCodable {
var aID: String
@Keyed("name")
var aName: String
@KeyedTransform(ToolBox.doubleTransform)
var AGrade: Int
}
// MARK: - ToolBox
enum ToolBox {
static let doubleTransform = SCTransformOf<Int, Double> {
(double) -> Int in
Int(double)
} toEncoder: { (int) -> Double in
Double(int) * 10
}
}