/
Decode.swift
49 lines (41 loc) · 1.34 KB
/
Decode.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
/*
Stork > Decode
This module offers tools to:
- decode a value of type T from 'Any' [Top-Level]
- decode values of type T from a JSON object [Nested]
Such type 'T' is required, at compile time, to comply
to the 'FromJson' protocol.
*/
infix operator .? // Maybe get a scalar or custom type
infix operator .! // Same as .? but expects the value to be present
infix operator ..? // Maybe get an array of scalar or custom types
infix operator ..! // Same as ..? but expects the array to be present
func .?<T>(json: JSON, key: String) -> T? where T: FromJson {
return json[key].flatMap(decodeValue)
}
func .!<T>(json: JSON, key: String) -> T where T: FromJson {
return (json .? key)!
}
func ..?<T>(json: JSON, key: String) -> [T]? where T: FromJson {
return json[key]
.map { value in
(value as? Array<Any>)?.compactMap(decodeValue) ?? []
}
}
func ..!<T>(json: JSON, key: String) -> [T] where T: FromJson {
return (json ..? key)!
}
func decodeValue<T>(_ value: Any) -> T? where T: FromJson {
switch value {
case is Bool:
return T.from(value: .boolean(value as! Bool))
case is Int:
return T.from(value: .int(value as! Int))
case is String:
return T.from(value: .string(value as! String))
case is JSON:
return T.from(value: .object(value as! JSON))
default:
return nil
}
}