forked from takaaptech/Freddy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSONEncodable.swift
83 lines (72 loc) · 2.65 KB
/
JSONEncodable.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// JSONEncodable.swift
// Freddy
//
// Created by Matthew Mathias on 1/4/16.
// Copyright © 2016 Big Nerd Ranch. All rights reserved.
//
import Foundation
/// A protocol to facilitate encoding and decoding of `JSON`.
public protocol JSONEncodable {
/// Converts an instance of a conforming type to `JSON`.
/// - returns: An instance of `JSON`.
/// - Note: If conforming to `JSONEncodable` with a custom type of your own, you should return an instance of
/// `JSON.Dictionary`.
func toJSON() -> JSON
}
extension Array where Element: JSONEncodable {
/// Converts an instance of `Array` whose elements conform to `JSONEncodable` to `JSON`.
/// - returns: An instance of `JSON` where the enum case is `.Array`.
public func toJSON() -> JSON {
let arrayOfJSON = self.map { $0.toJSON() }
return .Array(arrayOfJSON)
}
}
extension Dictionary where Value: JSONEncodable {
/// Converts an instance of `Dictionary` whose values conform to `JSONEncodable` to `JSON`. The keys in the resulting
/// `JSON.Dictionary` will be of type `String`.
/// - returns: An instance of `JSON` where the enum case is `.Dictionary`.
public func toJSON() -> JSON {
var jsonDictionary = [String: JSON]()
for (k, v) in self {
let key = String(k)
jsonDictionary[key] = v.toJSON()
}
return .Dictionary(jsonDictionary)
}
}
extension Int: JSONEncodable {
/// Converts an instance of a conforming type to `JSON`.
/// - returns: An instance of `JSON` where the enum case is `.Int`.
public func toJSON() -> JSON {
return .Int(self)
}
}
extension Double: JSONEncodable {
/// Converts an instance of a conforming type to `JSON`.
/// - returns: An instance of `JSON` where the enum case is `.Double`.
public func toJSON() -> JSON {
return .Double(self)
}
}
extension String: JSONEncodable {
/// Converts an instance of a conforming type to `JSON`.
/// - returns: An instance of `JSON` where the enum case is `.String`.
public func toJSON() -> JSON {
return .String(self)
}
}
extension Bool: JSONEncodable {
/// Converts an instance of a conforming type to `JSON`.
/// - returns: An instance of `JSON` where the enum case is `.Bool`.
public func toJSON() -> JSON {
return .Bool(self)
}
}
extension RawRepresentable where RawValue: JSONEncodable {
/// Converts an instance of a conforming type to `JSON`.
/// - returns: An instance of `JSON` where the enum case is whatever the underlying `RawValue` converts to.
public func toJSON() -> JSON {
return rawValue.toJSON()
}
}