From 42cef01e4ca75c661aefedeb626c41279621aadf Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Tue, 18 Apr 2017 00:19:08 +0800 Subject: [PATCH] Add double --- JSON/JSON.swift | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/JSON/JSON.swift b/JSON/JSON.swift index 2c99ed4..34f2bf0 100644 --- a/JSON/JSON.swift +++ b/JSON/JSON.swift @@ -85,6 +85,15 @@ public struct JSON { } } + public var double: Double? { + get { + return self.value as? Double + } + set { + self.value = newValue.flatMap({ $0 as NSObject}) + } + } + public var string: String? { get { return self.value as? String @@ -120,3 +129,42 @@ public struct JSON { } } + +extension JSON: ExpressibleByDictionaryLiteral { + + public typealias Key = String + public typealias Value = Any + public init(dictionaryLiteral elements: (JSON.Key, JSON.Value)...) { + var dictionary:[Key: Value] = [:] + elements.forEach({ dictionary[$0.0] = $0.1 }) + self.init(value: dictionary as NSDictionary) + } + +} + +extension JSON: ExpressibleByArrayLiteral { + + public typealias Element = Any + public init(arrayLiteral elements: JSON.Element...) { + self.init(value: elements as NSArray) + } + +} + +extension JSON { + + public func encode() -> Data? { + return self.value.flatMap({ + try? JSONSerialization.data(withJSONObject: $0, options: []) + }) + } + + public var prettyJson: String? { + return self.value.flatMap({ + try? JSONSerialization.data(withJSONObject: $0, options: [.prettyPrinted]) + }).flatMap({ + String(data: $0, encoding: .utf8) + }) + } + +}