-
Notifications
You must be signed in to change notification settings - Fork 54
/
JSON.swift
50 lines (46 loc) · 1.48 KB
/
JSON.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
public enum JSON {
public enum Number {
case integer(Int)
case unsignedInteger(UInt)
case double(Double)
}
case object([String: JSON])
case array([JSON])
case number(JSON.Number)
case string(String)
case boolean(Bool)
case null
}
//
// TODO: refactor with
// https://github.com/apple/swift-evolution/blob/master/proposals/0080-failable-numeric-initializers.md
//
extension Int {
public init?(_ number: JSON.Number) {
switch number {
case let .integer(value) : self.init(value)
case let .unsignedInteger(value) where value <= UInt(Int.max) : self.init(value)
case let .double(value) where value <= Double(Int32.max): self.init(value)
default: return nil
}
}
}
extension UInt {
public init?(_ number: JSON.Number) {
switch number {
case let .integer(value) where value > 0 : self.init(value)
case let .unsignedInteger(value) : self.init(value)
case let .double(value) where value <= Double(UInt32.max): self.init(value)
default: return nil
}
}
}
extension Double {
public init(_ number: JSON.Number) {
switch number {
case let .integer(value) : self.init(value)
case let .unsignedInteger(value): self.init(value)
case let .double(value) : self.init(value)
}
}
}