PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/Pods/SwiftyJSON/Source/SwiftyJSON.swift

https://gitlab.com/joaopaulogalvao/browteco
Swift | 1378 lines | 1079 code | 160 blank | 139 comment | 148 complexity | e5c78b9203b030b984760ae7e586d0a5 MD5 | raw file
  1. // SwiftyJSON.swift
  2. //
  3. // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. // MARK: - Error
  24. ///Error domain
  25. public let ErrorDomain: String = "SwiftyJSONErrorDomain"
  26. ///Error code
  27. public let ErrorUnsupportedType: Int = 999
  28. public let ErrorIndexOutOfBounds: Int = 900
  29. public let ErrorWrongType: Int = 901
  30. public let ErrorNotExist: Int = 500
  31. public let ErrorInvalidJSON: Int = 490
  32. // MARK: - JSON Type
  33. /**
  34. JSON's type definitions.
  35. See http://www.json.org
  36. */
  37. public enum Type :Int{
  38. case Number
  39. case String
  40. case Bool
  41. case Array
  42. case Dictionary
  43. case Null
  44. case Unknown
  45. }
  46. // MARK: - JSON Base
  47. public struct JSON {
  48. /**
  49. Creates a JSON using the data.
  50. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
  51. - parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
  52. - parameter error: error The NSErrorPointer used to return the error. `nil` by default.
  53. - returns: The created JSON
  54. */
  55. public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
  56. do {
  57. let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
  58. self.init(object)
  59. } catch let aError as NSError {
  60. if error != nil {
  61. error.memory = aError
  62. }
  63. self.init(NSNull())
  64. }
  65. }
  66. /**
  67. Create a JSON from JSON string
  68. - parameter string: Normal json string like '{"a":"b"}'
  69. - returns: The created JSON
  70. */
  71. public static func parse(string:String) -> JSON {
  72. return string.dataUsingEncoding(NSUTF8StringEncoding)
  73. .flatMap({JSON(data: $0)}) ?? JSON(NSNull())
  74. }
  75. /**
  76. Creates a JSON using the object.
  77. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
  78. - returns: The created JSON
  79. */
  80. public init(_ object: AnyObject) {
  81. self.object = object
  82. }
  83. /**
  84. Creates a JSON from a [JSON]
  85. - parameter jsonArray: A Swift array of JSON objects
  86. - returns: The created JSON
  87. */
  88. public init(_ jsonArray:[JSON]) {
  89. self.init(jsonArray.map { $0.object })
  90. }
  91. /**
  92. Creates a JSON from a [String: JSON]
  93. - parameter jsonDictionary: A Swift dictionary of JSON objects
  94. - returns: The created JSON
  95. */
  96. public init(_ jsonDictionary:[String: JSON]) {
  97. var dictionary = [String: AnyObject](minimumCapacity: jsonDictionary.count)
  98. for (key, json) in jsonDictionary {
  99. dictionary[key] = json.object
  100. }
  101. self.init(dictionary)
  102. }
  103. /// Private object
  104. private var rawArray: [AnyObject] = []
  105. private var rawDictionary: [String : AnyObject] = [:]
  106. private var rawString: String = ""
  107. private var rawNumber: NSNumber = 0
  108. private var rawNull: NSNull = NSNull()
  109. /// Private type
  110. private var _type: Type = .Null
  111. /// prviate error
  112. private var _error: NSError? = nil
  113. /// Object in JSON
  114. public var object: AnyObject {
  115. get {
  116. switch self.type {
  117. case .Array:
  118. return self.rawArray
  119. case .Dictionary:
  120. return self.rawDictionary
  121. case .String:
  122. return self.rawString
  123. case .Number:
  124. return self.rawNumber
  125. case .Bool:
  126. return self.rawNumber
  127. default:
  128. return self.rawNull
  129. }
  130. }
  131. set {
  132. _error = nil
  133. switch newValue {
  134. case let number as NSNumber:
  135. if number.isBool {
  136. _type = .Bool
  137. } else {
  138. _type = .Number
  139. }
  140. self.rawNumber = number
  141. case let string as String:
  142. _type = .String
  143. self.rawString = string
  144. case _ as NSNull:
  145. _type = .Null
  146. case let array as [AnyObject]:
  147. _type = .Array
  148. self.rawArray = array
  149. case let dictionary as [String : AnyObject]:
  150. _type = .Dictionary
  151. self.rawDictionary = dictionary
  152. default:
  153. _type = .Unknown
  154. _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
  155. }
  156. }
  157. }
  158. /// json type
  159. public var type: Type { get { return _type } }
  160. /// Error in JSON
  161. public var error: NSError? { get { return self._error } }
  162. /// The static null json
  163. @available(*, unavailable, renamed="null")
  164. public static var nullJSON: JSON { get { return null } }
  165. public static var null: JSON { get { return JSON(NSNull()) } }
  166. }
  167. // MARK: - CollectionType, SequenceType, Indexable
  168. extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable {
  169. public typealias Generator = JSONGenerator
  170. public typealias Index = JSONIndex
  171. public var startIndex: JSON.Index {
  172. switch self.type {
  173. case .Array:
  174. return JSONIndex(arrayIndex: self.rawArray.startIndex)
  175. case .Dictionary:
  176. return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex)
  177. default:
  178. return JSONIndex()
  179. }
  180. }
  181. public var endIndex: JSON.Index {
  182. switch self.type {
  183. case .Array:
  184. return JSONIndex(arrayIndex: self.rawArray.endIndex)
  185. case .Dictionary:
  186. return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex)
  187. default:
  188. return JSONIndex()
  189. }
  190. }
  191. public subscript (position: JSON.Index) -> JSON.Generator.Element {
  192. switch self.type {
  193. case .Array:
  194. return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!]))
  195. case .Dictionary:
  196. let (key, value) = self.rawDictionary[position.dictionaryIndex!]
  197. return (key, JSON(value))
  198. default:
  199. return ("", JSON.null)
  200. }
  201. }
  202. /// If `type` is `.Array` or `.Dictionary`, return `array.isEmpty` or `dictonary.isEmpty` otherwise return `true`.
  203. public var isEmpty: Bool {
  204. get {
  205. switch self.type {
  206. case .Array:
  207. return self.rawArray.isEmpty
  208. case .Dictionary:
  209. return self.rawDictionary.isEmpty
  210. default:
  211. return true
  212. }
  213. }
  214. }
  215. /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
  216. public var count: Int {
  217. switch self.type {
  218. case .Array:
  219. return self.rawArray.count
  220. case .Dictionary:
  221. return self.rawDictionary.count
  222. default:
  223. return 0
  224. }
  225. }
  226. public func underestimateCount() -> Int {
  227. switch self.type {
  228. case .Array:
  229. return self.rawArray.underestimateCount()
  230. case .Dictionary:
  231. return self.rawDictionary.underestimateCount()
  232. default:
  233. return 0
  234. }
  235. }
  236. /**
  237. If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty.
  238. - returns: Return a *generator* over the elements of JSON.
  239. */
  240. public func generate() -> JSON.Generator {
  241. return JSON.Generator(self)
  242. }
  243. }
  244. public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable {
  245. let arrayIndex: Int?
  246. let dictionaryIndex: DictionaryIndex<String, AnyObject>?
  247. let type: Type
  248. init(){
  249. self.arrayIndex = nil
  250. self.dictionaryIndex = nil
  251. self.type = .Unknown
  252. }
  253. init(arrayIndex: Int) {
  254. self.arrayIndex = arrayIndex
  255. self.dictionaryIndex = nil
  256. self.type = .Array
  257. }
  258. init(dictionaryIndex: DictionaryIndex<String, AnyObject>) {
  259. self.arrayIndex = nil
  260. self.dictionaryIndex = dictionaryIndex
  261. self.type = .Dictionary
  262. }
  263. public func successor() -> JSONIndex {
  264. switch self.type {
  265. case .Array:
  266. return JSONIndex(arrayIndex: self.arrayIndex!.successor())
  267. case .Dictionary:
  268. return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor())
  269. default:
  270. return JSONIndex()
  271. }
  272. }
  273. }
  274. public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  275. switch (lhs.type, rhs.type) {
  276. case (.Array, .Array):
  277. return lhs.arrayIndex == rhs.arrayIndex
  278. case (.Dictionary, .Dictionary):
  279. return lhs.dictionaryIndex == rhs.dictionaryIndex
  280. default:
  281. return false
  282. }
  283. }
  284. public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  285. switch (lhs.type, rhs.type) {
  286. case (.Array, .Array):
  287. return lhs.arrayIndex < rhs.arrayIndex
  288. case (.Dictionary, .Dictionary):
  289. return lhs.dictionaryIndex < rhs.dictionaryIndex
  290. default:
  291. return false
  292. }
  293. }
  294. public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  295. switch (lhs.type, rhs.type) {
  296. case (.Array, .Array):
  297. return lhs.arrayIndex <= rhs.arrayIndex
  298. case (.Dictionary, .Dictionary):
  299. return lhs.dictionaryIndex <= rhs.dictionaryIndex
  300. default:
  301. return false
  302. }
  303. }
  304. public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  305. switch (lhs.type, rhs.type) {
  306. case (.Array, .Array):
  307. return lhs.arrayIndex >= rhs.arrayIndex
  308. case (.Dictionary, .Dictionary):
  309. return lhs.dictionaryIndex >= rhs.dictionaryIndex
  310. default:
  311. return false
  312. }
  313. }
  314. public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  315. switch (lhs.type, rhs.type) {
  316. case (.Array, .Array):
  317. return lhs.arrayIndex > rhs.arrayIndex
  318. case (.Dictionary, .Dictionary):
  319. return lhs.dictionaryIndex > rhs.dictionaryIndex
  320. default:
  321. return false
  322. }
  323. }
  324. public struct JSONGenerator : GeneratorType {
  325. public typealias Element = (String, JSON)
  326. private let type: Type
  327. private var dictionayGenerate: DictionaryGenerator<String, AnyObject>?
  328. private var arrayGenerate: IndexingGenerator<[AnyObject]>?
  329. private var arrayIndex: Int = 0
  330. init(_ json: JSON) {
  331. self.type = json.type
  332. if type == .Array {
  333. self.arrayGenerate = json.rawArray.generate()
  334. }else {
  335. self.dictionayGenerate = json.rawDictionary.generate()
  336. }
  337. }
  338. public mutating func next() -> JSONGenerator.Element? {
  339. switch self.type {
  340. case .Array:
  341. if let o = self.arrayGenerate?.next() {
  342. let i = self.arrayIndex
  343. self.arrayIndex += 1
  344. return (String(i), JSON(o))
  345. } else {
  346. return nil
  347. }
  348. case .Dictionary:
  349. if let (k, v): (String, AnyObject) = self.dictionayGenerate?.next() {
  350. return (k, JSON(v))
  351. } else {
  352. return nil
  353. }
  354. default:
  355. return nil
  356. }
  357. }
  358. }
  359. // MARK: - Subscript
  360. /**
  361. * To mark both String and Int can be used in subscript.
  362. */
  363. public enum JSONKey {
  364. case Index(Int)
  365. case Key(String)
  366. }
  367. public protocol JSONSubscriptType {
  368. var jsonKey:JSONKey { get }
  369. }
  370. extension Int: JSONSubscriptType {
  371. public var jsonKey:JSONKey {
  372. return JSONKey.Index(self)
  373. }
  374. }
  375. extension String: JSONSubscriptType {
  376. public var jsonKey:JSONKey {
  377. return JSONKey.Key(self)
  378. }
  379. }
  380. extension JSON {
  381. /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error.
  382. private subscript(index index: Int) -> JSON {
  383. get {
  384. if self.type != .Array {
  385. var r = JSON.null
  386. r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
  387. return r
  388. } else if index >= 0 && index < self.rawArray.count {
  389. return JSON(self.rawArray[index])
  390. } else {
  391. var r = JSON.null
  392. r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
  393. return r
  394. }
  395. }
  396. set {
  397. if self.type == .Array {
  398. if self.rawArray.count > index && newValue.error == nil {
  399. self.rawArray[index] = newValue.object
  400. }
  401. }
  402. }
  403. }
  404. /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error.
  405. private subscript(key key: String) -> JSON {
  406. get {
  407. var r = JSON.null
  408. if self.type == .Dictionary {
  409. if let o = self.rawDictionary[key] {
  410. r = JSON(o)
  411. } else {
  412. r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
  413. }
  414. } else {
  415. r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
  416. }
  417. return r
  418. }
  419. set {
  420. if self.type == .Dictionary && newValue.error == nil {
  421. self.rawDictionary[key] = newValue.object
  422. }
  423. }
  424. }
  425. /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
  426. private subscript(sub sub: JSONSubscriptType) -> JSON {
  427. get {
  428. switch sub.jsonKey {
  429. case .Index(let index): return self[index: index]
  430. case .Key(let key): return self[key: key]
  431. }
  432. }
  433. set {
  434. switch sub.jsonKey {
  435. case .Index(let index): self[index: index] = newValue
  436. case .Key(let key): self[key: key] = newValue
  437. }
  438. }
  439. }
  440. /**
  441. Find a json in the complex data structuresby using the Int/String's array.
  442. - parameter path: The target json's path. Example:
  443. let json = JSON[data]
  444. let path = [9,"list","person","name"]
  445. let name = json[path]
  446. The same as: let name = json[9]["list"]["person"]["name"]
  447. - returns: Return a json found by the path or a null json with error
  448. */
  449. public subscript(path: [JSONSubscriptType]) -> JSON {
  450. get {
  451. return path.reduce(self) { $0[sub: $1] }
  452. }
  453. set {
  454. switch path.count {
  455. case 0:
  456. return
  457. case 1:
  458. self[sub:path[0]].object = newValue.object
  459. default:
  460. var aPath = path; aPath.removeAtIndex(0)
  461. var nextJSON = self[sub: path[0]]
  462. nextJSON[aPath] = newValue
  463. self[sub: path[0]] = nextJSON
  464. }
  465. }
  466. }
  467. /**
  468. Find a json in the complex data structures by using the Int/String's array.
  469. - parameter path: The target json's path. Example:
  470. let name = json[9,"list","person","name"]
  471. The same as: let name = json[9]["list"]["person"]["name"]
  472. - returns: Return a json found by the path or a null json with error
  473. */
  474. public subscript(path: JSONSubscriptType...) -> JSON {
  475. get {
  476. return self[path]
  477. }
  478. set {
  479. self[path] = newValue
  480. }
  481. }
  482. }
  483. // MARK: - LiteralConvertible
  484. extension JSON: Swift.StringLiteralConvertible {
  485. public init(stringLiteral value: StringLiteralType) {
  486. self.init(value)
  487. }
  488. public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
  489. self.init(value)
  490. }
  491. public init(unicodeScalarLiteral value: StringLiteralType) {
  492. self.init(value)
  493. }
  494. }
  495. extension JSON: Swift.IntegerLiteralConvertible {
  496. public init(integerLiteral value: IntegerLiteralType) {
  497. self.init(value)
  498. }
  499. }
  500. extension JSON: Swift.BooleanLiteralConvertible {
  501. public init(booleanLiteral value: BooleanLiteralType) {
  502. self.init(value)
  503. }
  504. }
  505. extension JSON: Swift.FloatLiteralConvertible {
  506. public init(floatLiteral value: FloatLiteralType) {
  507. self.init(value)
  508. }
  509. }
  510. extension JSON: Swift.DictionaryLiteralConvertible {
  511. public init(dictionaryLiteral elements: (String, AnyObject)...) {
  512. self.init(elements.reduce([String : AnyObject](minimumCapacity: elements.count)){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in
  513. var d = dictionary
  514. d[element.0] = element.1
  515. return d
  516. })
  517. }
  518. }
  519. extension JSON: Swift.ArrayLiteralConvertible {
  520. public init(arrayLiteral elements: AnyObject...) {
  521. self.init(elements)
  522. }
  523. }
  524. extension JSON: Swift.NilLiteralConvertible {
  525. public init(nilLiteral: ()) {
  526. self.init(NSNull())
  527. }
  528. }
  529. // MARK: - Raw
  530. extension JSON: Swift.RawRepresentable {
  531. public init?(rawValue: AnyObject) {
  532. if JSON(rawValue).type == .Unknown {
  533. return nil
  534. } else {
  535. self.init(rawValue)
  536. }
  537. }
  538. public var rawValue: AnyObject {
  539. return self.object
  540. }
  541. public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
  542. guard NSJSONSerialization.isValidJSONObject(self.object) else {
  543. throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"])
  544. }
  545. return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
  546. }
  547. public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
  548. switch self.type {
  549. case .Array, .Dictionary:
  550. do {
  551. let data = try self.rawData(options: opt)
  552. return NSString(data: data, encoding: encoding) as? String
  553. } catch _ {
  554. return nil
  555. }
  556. case .String:
  557. return self.rawString
  558. case .Number:
  559. return self.rawNumber.stringValue
  560. case .Bool:
  561. return self.rawNumber.boolValue.description
  562. case .Null:
  563. return "null"
  564. default:
  565. return nil
  566. }
  567. }
  568. }
  569. // MARK: - Printable, DebugPrintable
  570. extension JSON: Swift.Printable, Swift.DebugPrintable {
  571. public var description: String {
  572. if let string = self.rawString(options:.PrettyPrinted) {
  573. return string
  574. } else {
  575. return "unknown"
  576. }
  577. }
  578. public var debugDescription: String {
  579. return description
  580. }
  581. }
  582. // MARK: - Array
  583. extension JSON {
  584. //Optional [JSON]
  585. public var array: [JSON]? {
  586. get {
  587. if self.type == .Array {
  588. return self.rawArray.map{ JSON($0) }
  589. } else {
  590. return nil
  591. }
  592. }
  593. }
  594. //Non-optional [JSON]
  595. public var arrayValue: [JSON] {
  596. get {
  597. return self.array ?? []
  598. }
  599. }
  600. //Optional [AnyObject]
  601. public var arrayObject: [AnyObject]? {
  602. get {
  603. switch self.type {
  604. case .Array:
  605. return self.rawArray
  606. default:
  607. return nil
  608. }
  609. }
  610. set {
  611. if let array = newValue {
  612. self.object = array
  613. } else {
  614. self.object = NSNull()
  615. }
  616. }
  617. }
  618. }
  619. // MARK: - Dictionary
  620. extension JSON {
  621. //Optional [String : JSON]
  622. public var dictionary: [String : JSON]? {
  623. if self.type == .Dictionary {
  624. return self.rawDictionary.reduce([String : JSON](minimumCapacity: count)) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in
  625. var d = dictionary
  626. d[element.0] = JSON(element.1)
  627. return d
  628. }
  629. } else {
  630. return nil
  631. }
  632. }
  633. //Non-optional [String : JSON]
  634. public var dictionaryValue: [String : JSON] {
  635. return self.dictionary ?? [:]
  636. }
  637. //Optional [String : AnyObject]
  638. public var dictionaryObject: [String : AnyObject]? {
  639. get {
  640. switch self.type {
  641. case .Dictionary:
  642. return self.rawDictionary
  643. default:
  644. return nil
  645. }
  646. }
  647. set {
  648. if let v = newValue {
  649. self.object = v
  650. } else {
  651. self.object = NSNull()
  652. }
  653. }
  654. }
  655. }
  656. // MARK: - Bool
  657. extension JSON: Swift.BooleanType {
  658. //Optional bool
  659. public var bool: Bool? {
  660. get {
  661. switch self.type {
  662. case .Bool:
  663. return self.rawNumber.boolValue
  664. default:
  665. return nil
  666. }
  667. }
  668. set {
  669. if let newValue = newValue {
  670. self.object = NSNumber(bool: newValue)
  671. } else {
  672. self.object = NSNull()
  673. }
  674. }
  675. }
  676. //Non-optional bool
  677. public var boolValue: Bool {
  678. get {
  679. switch self.type {
  680. case .Bool, .Number, .String:
  681. return self.object.boolValue
  682. default:
  683. return false
  684. }
  685. }
  686. set {
  687. self.object = NSNumber(bool: newValue)
  688. }
  689. }
  690. }
  691. // MARK: - String
  692. extension JSON {
  693. //Optional string
  694. public var string: String? {
  695. get {
  696. switch self.type {
  697. case .String:
  698. return self.object as? String
  699. default:
  700. return nil
  701. }
  702. }
  703. set {
  704. if let newValue = newValue {
  705. self.object = NSString(string:newValue)
  706. } else {
  707. self.object = NSNull()
  708. }
  709. }
  710. }
  711. //Non-optional string
  712. public var stringValue: String {
  713. get {
  714. switch self.type {
  715. case .String:
  716. return self.object as? String ?? ""
  717. case .Number:
  718. return self.object.stringValue
  719. case .Bool:
  720. return (self.object as? Bool).map { String($0) } ?? ""
  721. default:
  722. return ""
  723. }
  724. }
  725. set {
  726. self.object = NSString(string:newValue)
  727. }
  728. }
  729. }
  730. // MARK: - Number
  731. extension JSON {
  732. //Optional number
  733. public var number: NSNumber? {
  734. get {
  735. switch self.type {
  736. case .Number, .Bool:
  737. return self.rawNumber
  738. default:
  739. return nil
  740. }
  741. }
  742. set {
  743. self.object = newValue ?? NSNull()
  744. }
  745. }
  746. //Non-optional number
  747. public var numberValue: NSNumber {
  748. get {
  749. switch self.type {
  750. case .String:
  751. let decimal = NSDecimalNumber(string: self.object as? String)
  752. if decimal == NSDecimalNumber.notANumber() { // indicates parse error
  753. return NSDecimalNumber.zero()
  754. }
  755. return decimal
  756. case .Number, .Bool:
  757. return self.object as? NSNumber ?? NSNumber(int: 0)
  758. default:
  759. return NSNumber(double: 0.0)
  760. }
  761. }
  762. set {
  763. self.object = newValue
  764. }
  765. }
  766. }
  767. //MARK: - Null
  768. extension JSON {
  769. public var null: NSNull? {
  770. get {
  771. switch self.type {
  772. case .Null:
  773. return self.rawNull
  774. default:
  775. return nil
  776. }
  777. }
  778. set {
  779. self.object = NSNull()
  780. }
  781. }
  782. public func exists() -> Bool{
  783. if let errorValue = error where errorValue.code == ErrorNotExist{
  784. return false
  785. }
  786. return true
  787. }
  788. }
  789. //MARK: - URL
  790. extension JSON {
  791. //Optional URL
  792. public var URL: NSURL? {
  793. get {
  794. switch self.type {
  795. case .String:
  796. if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
  797. return NSURL(string: encodedString_)
  798. } else {
  799. return nil
  800. }
  801. default:
  802. return nil
  803. }
  804. }
  805. set {
  806. self.object = newValue?.absoluteString ?? NSNull()
  807. }
  808. }
  809. }
  810. // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
  811. extension JSON {
  812. public var double: Double? {
  813. get {
  814. return self.number?.doubleValue
  815. }
  816. set {
  817. if let newValue = newValue {
  818. self.object = NSNumber(double: newValue)
  819. } else {
  820. self.object = NSNull()
  821. }
  822. }
  823. }
  824. public var doubleValue: Double {
  825. get {
  826. return self.numberValue.doubleValue
  827. }
  828. set {
  829. self.object = NSNumber(double: newValue)
  830. }
  831. }
  832. public var float: Float? {
  833. get {
  834. return self.number?.floatValue
  835. }
  836. set {
  837. if let newValue = newValue {
  838. self.object = NSNumber(float: newValue)
  839. } else {
  840. self.object = NSNull()
  841. }
  842. }
  843. }
  844. public var floatValue: Float {
  845. get {
  846. return self.numberValue.floatValue
  847. }
  848. set {
  849. self.object = NSNumber(float: newValue)
  850. }
  851. }
  852. public var int: Int? {
  853. get {
  854. return self.number?.longValue
  855. }
  856. set {
  857. if let newValue = newValue {
  858. self.object = NSNumber(integer: newValue)
  859. } else {
  860. self.object = NSNull()
  861. }
  862. }
  863. }
  864. public var intValue: Int {
  865. get {
  866. return self.numberValue.integerValue
  867. }
  868. set {
  869. self.object = NSNumber(integer: newValue)
  870. }
  871. }
  872. public var uInt: UInt? {
  873. get {
  874. return self.number?.unsignedLongValue
  875. }
  876. set {
  877. if let newValue = newValue {
  878. self.object = NSNumber(unsignedLong: newValue)
  879. } else {
  880. self.object = NSNull()
  881. }
  882. }
  883. }
  884. public var uIntValue: UInt {
  885. get {
  886. return self.numberValue.unsignedLongValue
  887. }
  888. set {
  889. self.object = NSNumber(unsignedLong: newValue)
  890. }
  891. }
  892. public var int8: Int8? {
  893. get {
  894. return self.number?.charValue
  895. }
  896. set {
  897. if let newValue = newValue {
  898. self.object = NSNumber(char: newValue)
  899. } else {
  900. self.object = NSNull()
  901. }
  902. }
  903. }
  904. public var int8Value: Int8 {
  905. get {
  906. return self.numberValue.charValue
  907. }
  908. set {
  909. self.object = NSNumber(char: newValue)
  910. }
  911. }
  912. public var uInt8: UInt8? {
  913. get {
  914. return self.number?.unsignedCharValue
  915. }
  916. set {
  917. if let newValue = newValue {
  918. self.object = NSNumber(unsignedChar: newValue)
  919. } else {
  920. self.object = NSNull()
  921. }
  922. }
  923. }
  924. public var uInt8Value: UInt8 {
  925. get {
  926. return self.numberValue.unsignedCharValue
  927. }
  928. set {
  929. self.object = NSNumber(unsignedChar: newValue)
  930. }
  931. }
  932. public var int16: Int16? {
  933. get {
  934. return self.number?.shortValue
  935. }
  936. set {
  937. if let newValue = newValue {
  938. self.object = NSNumber(short: newValue)
  939. } else {
  940. self.object = NSNull()
  941. }
  942. }
  943. }
  944. public var int16Value: Int16 {
  945. get {
  946. return self.numberValue.shortValue
  947. }
  948. set {
  949. self.object = NSNumber(short: newValue)
  950. }
  951. }
  952. public var uInt16: UInt16? {
  953. get {
  954. return self.number?.unsignedShortValue
  955. }
  956. set {
  957. if let newValue = newValue {
  958. self.object = NSNumber(unsignedShort: newValue)
  959. } else {
  960. self.object = NSNull()
  961. }
  962. }
  963. }
  964. public var uInt16Value: UInt16 {
  965. get {
  966. return self.numberValue.unsignedShortValue
  967. }
  968. set {
  969. self.object = NSNumber(unsignedShort: newValue)
  970. }
  971. }
  972. public var int32: Int32? {
  973. get {
  974. return self.number?.intValue
  975. }
  976. set {
  977. if let newValue = newValue {
  978. self.object = NSNumber(int: newValue)
  979. } else {
  980. self.object = NSNull()
  981. }
  982. }
  983. }
  984. public var int32Value: Int32 {
  985. get {
  986. return self.numberValue.intValue
  987. }
  988. set {
  989. self.object = NSNumber(int: newValue)
  990. }
  991. }
  992. public var uInt32: UInt32? {
  993. get {
  994. return self.number?.unsignedIntValue
  995. }
  996. set {
  997. if let newValue = newValue {
  998. self.object = NSNumber(unsignedInt: newValue)
  999. } else {
  1000. self.object = NSNull()
  1001. }
  1002. }
  1003. }
  1004. public var uInt32Value: UInt32 {
  1005. get {
  1006. return self.numberValue.unsignedIntValue
  1007. }
  1008. set {
  1009. self.object = NSNumber(unsignedInt: newValue)
  1010. }
  1011. }
  1012. public var int64: Int64? {
  1013. get {
  1014. return self.number?.longLongValue
  1015. }
  1016. set {
  1017. if let newValue = newValue {
  1018. self.object = NSNumber(longLong: newValue)
  1019. } else {
  1020. self.object = NSNull()
  1021. }
  1022. }
  1023. }
  1024. public var int64Value: Int64 {
  1025. get {
  1026. return self.numberValue.longLongValue
  1027. }
  1028. set {
  1029. self.object = NSNumber(longLong: newValue)
  1030. }
  1031. }
  1032. public var uInt64: UInt64? {
  1033. get {
  1034. return self.number?.unsignedLongLongValue
  1035. }
  1036. set {
  1037. if let newValue = newValue {
  1038. self.object = NSNumber(unsignedLongLong: newValue)
  1039. } else {
  1040. self.object = NSNull()
  1041. }
  1042. }
  1043. }
  1044. public var uInt64Value: UInt64 {
  1045. get {
  1046. return self.numberValue.unsignedLongLongValue
  1047. }
  1048. set {
  1049. self.object = NSNumber(unsignedLongLong: newValue)
  1050. }
  1051. }
  1052. }
  1053. //MARK: - Comparable
  1054. extension JSON : Swift.Comparable {}
  1055. public func ==(lhs: JSON, rhs: JSON) -> Bool {
  1056. switch (lhs.type, rhs.type) {
  1057. case (.Number, .Number):
  1058. return lhs.rawNumber == rhs.rawNumber
  1059. case (.String, .String):
  1060. return lhs.rawString == rhs.rawString
  1061. case (.Bool, .Bool):
  1062. return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
  1063. case (.Array, .Array):
  1064. return lhs.rawArray as NSArray == rhs.rawArray as NSArray
  1065. case (.Dictionary, .Dictionary):
  1066. return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
  1067. case (.Null, .Null):
  1068. return true
  1069. default:
  1070. return false
  1071. }
  1072. }
  1073. public func <=(lhs: JSON, rhs: JSON) -> Bool {
  1074. switch (lhs.type, rhs.type) {
  1075. case (.Number, .Number):
  1076. return lhs.rawNumber <= rhs.rawNumber
  1077. case (.String, .String):
  1078. return lhs.rawString <= rhs.rawString
  1079. case (.Bool, .Bool):
  1080. return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
  1081. case (.Array, .Array):
  1082. return lhs.rawArray as NSArray == rhs.rawArray as NSArray
  1083. case (.Dictionary, .Dictionary):
  1084. return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
  1085. case (.Null, .Null):
  1086. return true
  1087. default:
  1088. return false
  1089. }
  1090. }
  1091. public func >=(lhs: JSON, rhs: JSON) -> Bool {
  1092. switch (lhs.type, rhs.type) {
  1093. case (.Number, .Number):
  1094. return lhs.rawNumber >= rhs.rawNumber
  1095. case (.String, .String):
  1096. return lhs.rawString >= rhs.rawString
  1097. case (.Bool, .Bool):
  1098. return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
  1099. case (.Array, .Array):
  1100. return lhs.rawArray as NSArray == rhs.rawArray as NSArray
  1101. case (.Dictionary, .Dictionary):
  1102. return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
  1103. case (.Null, .Null):
  1104. return true
  1105. default:
  1106. return false
  1107. }
  1108. }
  1109. public func >(lhs: JSON, rhs: JSON) -> Bool {
  1110. switch (lhs.type, rhs.type) {
  1111. case (.Number, .Number):
  1112. return lhs.rawNumber > rhs.rawNumber
  1113. case (.String, .String):
  1114. return lhs.rawString > rhs.rawString
  1115. default:
  1116. return false
  1117. }
  1118. }
  1119. public func <(lhs: JSON, rhs: JSON) -> Bool {
  1120. switch (lhs.type, rhs.type) {
  1121. case (.Number, .Number):
  1122. return lhs.rawNumber < rhs.rawNumber
  1123. case (.String, .String):
  1124. return lhs.rawString < rhs.rawString
  1125. default:
  1126. return false
  1127. }
  1128. }
  1129. private let trueNumber = NSNumber(bool: true)
  1130. private let falseNumber = NSNumber(bool: false)
  1131. private let trueObjCType = String.fromCString(trueNumber.objCType)
  1132. private let falseObjCType = String.fromCString(falseNumber.objCType)
  1133. // MARK: - NSNumber: Comparable
  1134. extension NSNumber {
  1135. var isBool:Bool {
  1136. get {
  1137. let objCType = String.fromCString(self.objCType)
  1138. if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType)
  1139. || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
  1140. return true
  1141. } else {
  1142. return false
  1143. }
  1144. }
  1145. }
  1146. }
  1147. func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1148. switch (lhs.isBool, rhs.isBool) {
  1149. case (false, true):
  1150. return false
  1151. case (true, false):
  1152. return false
  1153. default:
  1154. return lhs.compare(rhs) == NSComparisonResult.OrderedSame
  1155. }
  1156. }
  1157. func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1158. return !(lhs == rhs)
  1159. }
  1160. func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1161. switch (lhs.isBool, rhs.isBool) {
  1162. case (false, true):
  1163. return false
  1164. case (true, false):
  1165. return false
  1166. default:
  1167. return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
  1168. }
  1169. }
  1170. func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1171. switch (lhs.isBool, rhs.isBool) {
  1172. case (false, true):
  1173. return false
  1174. case (true, false):
  1175. return false
  1176. default:
  1177. return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
  1178. }
  1179. }
  1180. func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1181. switch (lhs.isBool, rhs.isBool) {
  1182. case (false, true):
  1183. return false
  1184. case (true, false):
  1185. return false
  1186. default:
  1187. return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
  1188. }
  1189. }
  1190. func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1191. switch (lhs.isBool, rhs.isBool) {
  1192. case (false, true):
  1193. return false
  1194. case (true, false):
  1195. return false
  1196. default:
  1197. return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
  1198. }
  1199. }