mirror of
https://github.com/github/semantic.git
synced 2024-12-12 14:45:40 +03:00
71 lines
1.4 KiB
Swift
71 lines
1.4 KiB
Swift
public enum JSON {
|
|
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
|
|
|
|
|
|
public var number: Double? {
|
|
if case let .Number(d) = self { return d }
|
|
return nil
|
|
}
|
|
|
|
public var boolean: Bool? {
|
|
if case let .Boolean(b) = self { return b }
|
|
return nil
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
public var isNull: Bool {
|
|
if case .Null = self { return true }
|
|
return false
|
|
}
|
|
|
|
public init?(object: AnyObject) {
|
|
struct E: ErrorType {}
|
|
func die<T>() throws -> T {
|
|
throw E()
|
|
}
|
|
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]:
|
|
self = .Array(try a.map { try JSON(object: $0) ?? die() })
|
|
case let d as [Swift.String:AnyObject]:
|
|
self = .Dictionary(Swift.Dictionary(elements: try d.map { ($0, try JSON(object: $1) ?? die()) }))
|
|
case is NSNull:
|
|
self = .Null
|
|
default:
|
|
return nil
|
|
}
|
|
} catch { return nil }
|
|
}
|
|
}
|
|
|
|
|
|
import Foundation
|