1
1
mirror of https://github.com/github/semantic.git synced 2024-12-12 14:45:40 +03:00
semantic/prototype/Doubt/JSON.swift

71 lines
1.4 KiB
Swift
Raw Normal View History

2015-09-21 22:23:16 +03:00
public enum JSON {
2015-09-23 18:34:35 +03:00
public typealias ArrayType = [JSON]
public typealias DictionaryType = [Swift.String:JSON]
case Number(Double)
case Boolean(Bool)
case String(Swift.String)
case Array(ArrayType)
case Dictionary(DictionaryType)
case Null
2015-09-21 22:23:16 +03:00
public var number: Double? {
if case let .Number(d) = self { return d }
return nil
}
2015-09-21 22:23:16 +03:00
public var boolean: Bool? {
if case let .Boolean(b) = self { return b }
return nil
}
2015-09-21 22:23:16 +03:00
public var string: Swift.String? {
if case let .String(s) = self { return s }
return nil
}
public var array: ArrayType? {
if case let .Array(a) = self { return a }
return nil
}
public var dictionary: DictionaryType? {
if case let .Dictionary(d) = self { return d }
return nil
}
2015-09-21 22:23:16 +03:00
public var isNull: Bool {
if case .Null = self { return true }
return false
}
2015-09-23 23:26:00 +03:00
public init?(object: AnyObject) {
2015-09-23 18:33:34 +03:00
struct E: ErrorType {}
func die<T>() throws -> T {
throw E()
}
2015-09-23 18:33:34 +03:00
do {
switch object {
case let n as Double:
self = .Number(n)
case let b as Bool:
self = .Boolean(b)
case let s as Swift.String:
self = .String(s)
case let a as [AnyObject]:
2015-09-23 18:34:35 +03:00
self = .Array(try a.map { try JSON(object: $0) ?? die() })
2015-09-23 18:33:34 +03:00
case let d as [Swift.String:AnyObject]:
2015-09-23 18:34:35 +03:00
self = .Dictionary(Swift.Dictionary(elements: try d.map { ($0, try JSON(object: $1) ?? die()) }))
2015-09-23 18:33:34 +03:00
case is NSNull:
self = .Null
default:
return nil
}
} catch { return nil }
}
}
import Foundation