-
Notifications
You must be signed in to change notification settings - Fork 50
/
StandardLib.swift
95 lines (78 loc) · 2.58 KB
/
StandardLib.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
84
85
86
87
88
89
90
91
92
93
94
95
//
// StandardLib.swift
// Himotoki
//
// Created by Syo Ikeda on 11/18/15.
// Copyright © 2015 Syo Ikeda. All rights reserved.
//
extension String: Decodable {
public static func decode(e: Extractor) throws -> String {
return try castOrFail(e)
}
}
extension Int: Decodable {
public static func decode(e: Extractor) throws -> Int {
return try castOrFail(e)
}
}
extension UInt: Decodable {
public static func decode(e: Extractor) throws -> UInt {
return try castOrFail(e)
}
}
extension Double: Decodable {
public static func decode(e: Extractor) throws -> Double {
return try castOrFail(e)
}
}
extension Float: Decodable {
public static func decode(e: Extractor) throws -> Float {
return try castOrFail(e)
}
}
extension Bool: Decodable {
public static func decode(e: Extractor) throws -> Bool {
return try castOrFail(e)
}
}
// MARK: - Extensions
extension CollectionType where Generator.Element: Decodable {
/// - Throws: DecodeError or an arbitrary ErrorType
public static func decode(JSON: AnyJSON) throws -> [Generator.Element] {
guard let array = JSON as? [AnyJSON] else {
throw typeMismatch("Array", actual: JSON, keyPath: nil)
}
return try array.map(Generator.Element.decodeValue)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public static func decode(JSON: AnyJSON, rootKeyPath: KeyPath) throws -> [Generator.Element] {
return try Extractor(JSON).array(rootKeyPath)
}
}
extension DictionaryLiteralConvertible where Value: Decodable {
/// - Throws: DecodeError or an arbitrary ErrorType
public static func decode(JSON: AnyJSON) throws -> [String: Value] {
guard let dictionary = JSON as? [String: AnyJSON] else {
throw typeMismatch("Dictionary", actual: JSON, keyPath: nil)
}
var result = [String: Value](minimumCapacity: dictionary.count)
try dictionary.forEach { key, value in
result[key] = try Value.decodeValue(value)
}
return result
}
/// - Throws: DecodeError or an arbitrary ErrorType
public static func decode(JSON: AnyJSON, rootKeyPath: KeyPath) throws -> [String: Value] {
return try Extractor(JSON).dictionary(rootKeyPath)
}
}
// MARK: Helpers
internal func castOrFail<T>(e: Extractor) throws -> T {
return try castOrFail(e.rawValue)
}
internal func castOrFail<T>(any: Any?) throws -> T {
guard let result = any as? T else {
throw typeMismatch("\(T.self)", actual: any, keyPath: nil)
}
return result
}