-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathJSONHelpers.swift
More file actions
61 lines (48 loc) · 1.35 KB
/
JSONHelpers.swift
File metadata and controls
61 lines (48 loc) · 1.35 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
//
// JSONHelpers.swift
// JSONCodable
//
// Created by Matthew Cheok on 17/7/15.
// Copyright © 2015 matthewcheok. All rights reserved.
//
// Convenience
public typealias JSONObject = [String: AnyObject]
// Dictionary handling
protocol JSONDictionary {
var count: Int { get }
func valuesAreJSONEncodable() -> Bool
func valuesMadeJSONEncodable() -> [String: JSONEncodable]
}
extension Dictionary : JSONDictionary {
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(k)] = v as? JSONEncodable
}
return dict
}
}
// Array handling
protocol JSONArray {
var count: Int { get }
func elementsAreJSONEncodable() -> Bool
func elementsMadeJSONEncodable() -> [JSONEncodable]
}
extension Array: JSONArray {
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 }
}