-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathJSONHelpers.swift
More file actions
73 lines (56 loc) · 1.62 KB
/
JSONHelpers.swift
File metadata and controls
73 lines (56 loc) · 1.62 KB
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
69
70
71
72
//
// JSONHelpers.swift
// JSONCodable
//
// Created by Matthew Cheok on 17/7/15.
// Copyright © 2015 matthewcheok. All rights reserved.
//
// Convenience
public typealias JSONObject = [String: Any]
// Dictionary handling
protocol JSONDictionary {
var count: Int { get }
func valuesAreJSONEncodable() -> Bool
func valuesMadeJSONEncodable() -> [String: JSONEncodable]
var valueType: Any.Type { get }
}
extension Dictionary : JSONDictionary {
var valueType: Any.Type {
return Value.self
}
func valuesAreJSONEncodable() -> Bool {
return Key.self is String.Type && (Value.self is JSONEncodable.Type || Value.self is JSONEncodable.Protocol)
}
func valuesMadeJSONEncodable() -> [String: JSONEncodable] {
var dict: [String: JSONEncodable] = [:]
for (k, v) in self {
dict[String(describing:k)] = v as? JSONEncodable
}
return dict
}
}
// Array handling
protocol JSONArray {
var count: Int { get }
func elementsAreJSONEncodable() -> Bool
func elementsMadeJSONEncodable() -> [JSONEncodable]
var elementType: Any.Type { get }
}
extension Array: JSONArray {
var elementType: Any.Type {
return Element.self
}
func elementsAreJSONEncodable() -> Bool {
return Element.self is JSONEncodable.Type || Element.self is JSONEncodable.Protocol
}
func elementsMadeJSONEncodable() -> [JSONEncodable] {
return self.map {$0 as! JSONEncodable}
}
}
// Optional handling
protocol JSONOptional {
var wrapped: Any? { get }
}
extension Optional: JSONOptional {
var wrapped: Any? { return self }
}