From 1ddae138ebf0b9bacb2550bd8c14c13b03f96ea3 Mon Sep 17 00:00:00 2001 From: Adlai Holler Date: Tue, 8 Dec 2015 18:02:52 -0800 Subject: [PATCH 001/260] Use minimumCapacity parameter to optimize dictionary creations --- Source/SwiftyJSON.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index fa8635eb..472eb1f0 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -118,7 +118,7 @@ public struct JSON { - returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { - var dictionary = [String: AnyObject]() + var dictionary = [String: AnyObject](minimumCapacity: jsonDictionary.count) for (key, json) in jsonDictionary { dictionary[key] = json.object } @@ -596,7 +596,7 @@ extension JSON: Swift.FloatLiteralConvertible { extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { - self.init(elements.reduce([String : AnyObject]()){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in + self.init(elements.reduce([String : AnyObject](minimumCapacity: elements.count)){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in var d = dictionary d[element.0] = element.1 return d @@ -731,7 +731,7 @@ extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .Dictionary { - return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in + return self.rawDictionary.reduce([String : JSON](minimumCapacity: count)) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in var d = dictionary d[element.0] = JSON(element.1) return d From 60034664e8ca3d9174efda1aa93a2c07ae45292a Mon Sep 17 00:00:00 2001 From: Alexander Ney Date: Wed, 9 Dec 2015 14:42:27 +0000 Subject: [PATCH 002/260] set the watch os deployment target to watchOs 2.0 - otherwise it would have used always the most current one with the result that the lib is not usable with apps deploying on watchOS 2.0 --- SwiftyJSON.xcodeproj/project.pbxproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 8e95c29c..442f9818 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -970,6 +970,7 @@ SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos"; TARGETED_DEVICE_FAMILY = 4; + WATCHOS_DEPLOYMENT_TARGET = 2.0; }; name = Debug; }; @@ -992,6 +993,7 @@ SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos"; TARGETED_DEVICE_FAMILY = 4; + WATCHOS_DEPLOYMENT_TARGET = 2.0; }; name = Release; }; From 7620d5bc0fb4ad21c7dccbe6661b61a5f27b0545 Mon Sep 17 00:00:00 2001 From: Fernando Paredes Date: Mon, 21 Dec 2015 08:48:44 -0800 Subject: [PATCH 003/260] Programmatically set current tag --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index ee48960c..1a9d29dd 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -11,6 +11,6 @@ Pod::Spec.new do |s| s.ios.deployment_target = "8.0" s.watchos.deployment_target = "2.0" s.tvos.deployment_target = "9.0" - s.source = { :git => "https://github.com/SwiftyJSON/SwiftyJSON.git", :tag => "2.3.2"} + s.source = { :git => "https://github.com/SwiftyJSON/SwiftyJSON.git", :tag => s.version } s.source_files = "Source/*.swift" end From baf8c18655317439bf8d5e63d439c8fe40644112 Mon Sep 17 00:00:00 2001 From: Saagar Jha Date: Tue, 5 Jan 2016 17:06:56 -0800 Subject: [PATCH 004/260] Changed "Mac OS X" to "OS X" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OS X versions after OS X 10.8 Mountain dropped the “Mac” part of their name. Now matches rest of README as well. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ec3af393..2d854b92 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ if let userName = json[999999]["wrong_key"]["wrong_name"].string { ## Requirements -- iOS 7.0+ / Mac OS X 10.9+ +- iOS 7.0+ / OS X 10.9+ - Xcode 7 ##Integration From cbeddbc246ea18cb3e893452cd03085f830d4658 Mon Sep 17 00:00:00 2001 From: Danut Pralea Date: Tue, 12 Jan 2016 23:32:18 +0200 Subject: [PATCH 005/260] Update README.md typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2d854b92..75d51850 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ let package = Package( ) ``` -Note that the [Swift Package Manager](https://swift.org/package-manager) is still in early design and development, for more infomation checkout it's [GitHub Page](https://github.com/apple/swift-package-manager) +Note that the [Swift Package Manager](https://swift.org/package-manager) is still in early design and development, for more infomation checkout its [GitHub Page](https://github.com/apple/swift-package-manager) ####Manually (iOS 7+, OS X 10.9+) From 64b832c7f5f59a2ad132f738c332dbe53f766c69 Mon Sep 17 00:00:00 2001 From: Vijaya Prakash Kandel Date: Thu, 28 Jan 2016 16:45:37 +0100 Subject: [PATCH 006/260] Changed from .empty to .isEmpty The comment had array.empty which but it was implemented by array.isEmpty and similar for dictionary. Although the intent is clear, the comment suggested it was the code portion and it was mismatching. Thus, i think its necessary. --- Source/SwiftyJSON.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index fa8635eb..21b39d67 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -235,7 +235,7 @@ extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable { } } - /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `true`. + /// If `type` is `.Array` or `.Dictionary`, return `array.isEmpty` or `dictonary.isEmpty` otherwise return `true`. public var isEmpty: Bool { get { switch self.type { From 49f588e634c934bad0439aa5a0a13eaea8e931fc Mon Sep 17 00:00:00 2001 From: Vijaya Prakash Kandel Date: Sun, 31 Jan 2016 13:33:57 +0100 Subject: [PATCH 007/260] Which's -> whose and typo fix in comments - `which's` doesnot seem to make lot of sense so i think its better off by using `whose` - there was no space between `structuresby` which is changed to `structures by` --- Source/SwiftyJSON.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index fa8635eb..126563d9 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -440,7 +440,7 @@ extension String: JSONSubscriptType { extension JSON { - /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. + /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { @@ -464,7 +464,7 @@ extension JSON { } } - /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. + /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var r = JSON.null @@ -535,7 +535,7 @@ extension JSON { } /** - Find a json in the complex data structuresby using the Int/String's array. + Find a json in the complex data structures by using the Int/String's array. - parameter path: The target json's path. Example: From 9966411ad58c17aac831b2af9ea9035b461e1743 Mon Sep 17 00:00:00 2001 From: ReadmeCritic Date: Fri, 12 Feb 2016 19:33:44 -0800 Subject: [PATCH 008/260] Correct the spelling of CocoaPods in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75d51850..e616d7b0 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ if let userName = json[999999]["wrong_key"]["wrong_name"].string { ##Integration ####CocoaPods (iOS 8+, OS X 10.9+) -You can use [Cocoapods](http://cocoapods.org/) to install `SwiftyJSON`by adding it to your `Podfile`: +You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON`by adding it to your `Podfile`: ```ruby platform :ios, '8.0' use_frameworks! From 5fc4545c7a5d1fd4a2b3d04964f1bc593c356676 Mon Sep 17 00:00:00 2001 From: Craig Siemens Date: Wed, 17 Feb 2016 09:48:30 -0700 Subject: [PATCH 009/260] Rename isExists to exists. Fixes #448 --- Source/SwiftyJSON.swift | 2 +- Tests/BaseTests.swift | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index fa8635eb..15a1c3f8 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -904,7 +904,7 @@ extension JSON { self.object = NSNull() } } - public func isExists() -> Bool{ + public func exists() -> Bool{ if let errorValue = error where errorValue.code == ErrorNotExist{ return false } diff --git a/Tests/BaseTests.swift b/Tests/BaseTests.swift index 7b5b5dcd..a5d52f42 100644 --- a/Tests/BaseTests.swift +++ b/Tests/BaseTests.swift @@ -229,8 +229,8 @@ class BaseTests: XCTestCase { func testExistance() { let dictionary = ["number":1111] let json = JSON(dictionary) - XCTAssertFalse(json["unspecifiedValue"].isExists()) - XCTAssertTrue(json["number"].isExists()) + XCTAssertFalse(json["unspecifiedValue"].exists()) + XCTAssertTrue(json["number"].exists()) } func testErrorHandle() { From f0bbe53d891cfcb781d4e73f87b35a4b9c045b53 Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 18 Feb 2016 17:45:34 -0500 Subject: [PATCH 010/260] README typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75d51850..e62bd678 100644 --- a/README.md +++ b/README.md @@ -315,7 +315,7 @@ if let string = json.rawString() { //Do something you want } ``` -####Existance +####Existence ```swift //shows you whether value specified in JSON or not if json["name"].isExists() From 52cfeb54e05233e7f2b697a17a9b27e2fde524ff Mon Sep 17 00:00:00 2001 From: Victor Sigler Date: Mon, 29 Feb 2016 19:31:27 -0500 Subject: [PATCH 011/260] Update Alamofire code Update the Alamofire interaction with the new code for Alamofire 3, that in the `.Success` is returned its associated value as with the `error` in the case of `.Failure`. --- README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 75d51850..39e2c80a 100644 --- a/README.md +++ b/README.md @@ -380,11 +380,10 @@ SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: ```swift Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { - case .Success: - if let value = response.result.value { - let json = JSON(value) - print("JSON: \(json)") - } + case .Success(let value): + let json = JSON(value) + print("JSON: \(json)") + case .Failure(let error): print(error) } From d0ea821595e20874dcda32300155c3ec251cee59 Mon Sep 17 00:00:00 2001 From: Victor Sigler Date: Mon, 29 Feb 2016 19:32:39 -0500 Subject: [PATCH 012/260] Remove blank space --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 39e2c80a..113a65b2 100644 --- a/README.md +++ b/README.md @@ -383,7 +383,6 @@ Alamofire.request(.GET, url).validate().responseJSON { response in case .Success(let value): let json = JSON(value) print("JSON: \(json)") - case .Failure(let error): print(error) } From 20ee3ed7bd9e49c250d91f402f01fe87caeacf2a Mon Sep 17 00:00:00 2001 From: "Glenn R. Fisher" Date: Tue, 1 Mar 2016 11:23:14 -0600 Subject: [PATCH 013/260] Replace ++ with += The increment (++) and decrement (--) operators will be deprecated with Swift 3. For more information, see proposal SE-0004: https://github.com/apple/swift-evolution/blob/master/proposals/0004-remove-pre-post-inc-decrement.md --- Source/SwiftyJSON.swift | 4 +++- Tests/SequenceTypeTests.swift | 20 ++++++++++---------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index fa8635eb..418531f1 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -396,7 +396,9 @@ public struct JSONGenerator : GeneratorType { switch self.type { case .Array: if let o = self.arrayGenerate?.next() { - return (String(self.arrayIndex++), JSON(o)) + let i = self.arrayIndex + self.arrayIndex += 1 + return (String(i), JSON(o)) } else { return nil } diff --git a/Tests/SequenceTypeTests.swift b/Tests/SequenceTypeTests.swift index 6711a221..b3ea4b77 100644 --- a/Tests/SequenceTypeTests.swift +++ b/Tests/SequenceTypeTests.swift @@ -56,7 +56,7 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.number!) - index++ + index += 1 } XCTAssertEqual(index, 5) XCTAssertEqual(array, [1,2.0,3.3,123456789,987654321.123456789]) @@ -72,7 +72,7 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.bool!) - index++ + index += 1 } XCTAssertEqual(index, 5) XCTAssertEqual(array, [true, false, false, true, true]) @@ -88,7 +88,7 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.string!) - index++ + index += 1 } XCTAssertEqual(index, 3) XCTAssertEqual(array, ["aoo","bpp","zoo"]) @@ -104,7 +104,7 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.object) - index++ + index += 1 } XCTAssertEqual(index, 4) XCTAssertEqual(array[0] as? String, "aoo") @@ -121,7 +121,7 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.object) - index++ + index += 1 } XCTAssertEqual(index, 3) XCTAssertEqual((array[0] as! [String : Int])["1"]!, 1) @@ -140,7 +140,7 @@ class SequenceTypeTests: XCTestCase { for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.number! - index++ + index += 1 } XCTAssertEqual(index, 2) @@ -157,7 +157,7 @@ class SequenceTypeTests: XCTestCase { for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.bool! - index++ + index += 1 } XCTAssertEqual(index, 5) @@ -174,7 +174,7 @@ class SequenceTypeTests: XCTestCase { for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.string! - index++ + index += 1 } XCTAssertEqual(index, 3) @@ -191,7 +191,7 @@ class SequenceTypeTests: XCTestCase { for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.object - index++ + index += 1 } XCTAssertEqual(index, 4) @@ -210,7 +210,7 @@ class SequenceTypeTests: XCTestCase { for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.object - index++ + index += 1 } XCTAssertEqual(index, 3) From b3972382d06459a5ae1dea5e6672a7bdb96094f6 Mon Sep 17 00:00:00 2001 From: Karthik Gollapudi Date: Sun, 20 Mar 2016 17:49:53 -0700 Subject: [PATCH 014/260] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75d51850..e62bd678 100644 --- a/README.md +++ b/README.md @@ -315,7 +315,7 @@ if let string = json.rawString() { //Do something you want } ``` -####Existance +####Existence ```swift //shows you whether value specified in JSON or not if json["name"].isExists() From 71a006fef39b5a42ab8658542ccf0d0752f734b6 Mon Sep 17 00:00:00 2001 From: Shantanu Desai Date: Sun, 27 Mar 2016 13:58:35 +0530 Subject: [PATCH 015/260] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75d51850..ec44965d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ #SwiftyJSON [中文介绍](http://tangplin.github.io/swiftyjson/) -[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) +[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) SwiftyJSON makes it easy to deal with JSON data in Swift. From a121ac6ef15336a71b792f0998d275be32e18c2e Mon Sep 17 00:00:00 2001 From: Grant Kemp Date: Sat, 16 Apr 2016 19:53:41 +0100 Subject: [PATCH 016/260] errorFix: incorrect method specified in Readme. Fixed to ensure new users are not confused. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75d51850..ed0513fa 100644 --- a/README.md +++ b/README.md @@ -318,7 +318,7 @@ if let string = json.rawString() { ####Existance ```swift //shows you whether value specified in JSON or not -if json["name"].isExists() +if json["name"].exists() ``` ####Literal convertibles From a57e05c465cf9bb52316bfbdb4c6490847aaee2b Mon Sep 17 00:00:00 2001 From: Grant Kemp Date: Sat, 16 Apr 2016 19:54:08 +0100 Subject: [PATCH 017/260] admin : fixed some typos --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ed0513fa..63566e97 100644 --- a/README.md +++ b/README.md @@ -275,7 +275,7 @@ let id: Int = json["id"].intValue let name: String = json["name"].stringValue ``` ```swift -//If not a Array or nil, return [] +//If not an Array or nil, return [] let list: Array = json["list"].arrayValue ``` ```swift @@ -315,7 +315,7 @@ if let string = json.rawString() { //Do something you want } ``` -####Existance +####Existence ```swift //shows you whether value specified in JSON or not if json["name"].exists() From 6882c23c19d8c36811e9424daf458877032f4b81 Mon Sep 17 00:00:00 2001 From: Ruoyu Fu Date: Tue, 14 Jun 2016 16:12:31 -0700 Subject: [PATCH 018/260] Beta support for swift3. --- Source/SwiftyJSON.swift | 556 +++++++----------- SwiftyJSON.xcodeproj/project.pbxproj | 14 +- .../xcschemes/SwiftyJSON OSX.xcscheme | 10 +- .../xcschemes/SwiftyJSON iOS.xcscheme | 10 +- .../xcschemes/SwiftyJSON tvOS.xcscheme | 4 +- .../xcschemes/SwiftyJSON watchOS.xcscheme | 2 +- Tests/BaseTests.swift | 70 +-- Tests/ComparableTests.swift | 24 +- Tests/NumberTests.swift | 208 +++---- Tests/PerformanceTests.swift | 16 +- Tests/PrintableTests.swift | 20 +- Tests/RawRepresentableTests.swift | 6 +- Tests/RawTests.swift | 12 +- Tests/SequenceTypeTests.swift | 6 +- Tests/StringTests.swift | 6 +- Tests/SubscriptTests.swift | 4 +- 16 files changed, 411 insertions(+), 557 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 8a5b5d67..b639ac00 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -43,13 +43,13 @@ See http://www.json.org */ public enum Type :Int{ - case Number - case String - case Bool - case Array - case Dictionary - case Null - case Unknown + case number + case string + case bool + case array + case dictionary + case null + case unknown } // MARK: - JSON Base @@ -65,13 +65,13 @@ public struct JSON { - returns: The created JSON */ - public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { + public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer? = nil) { do { - let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) + let object: AnyObject = try JSONSerialization.jsonObject(with: data, options: opt) self.init(object) } catch let aError as NSError { if error != nil { - error.memory = aError + error??.pointee = aError } self.init(NSNull()) } @@ -83,8 +83,8 @@ public struct JSON { - returns: The created JSON */ - public static func parse(string:String) -> JSON { - return string.dataUsingEncoding(NSUTF8StringEncoding) + public static func parse(_ string:String) -> JSON { + return string.data(using: String.Encoding.utf8) .flatMap({JSON(data: $0)}) ?? JSON(NSNull()) } @@ -132,7 +132,7 @@ public struct JSON { private var rawNumber: NSNumber = 0 private var rawNull: NSNull = NSNull() /// Private type - private var _type: Type = .Null + private var _type: Type = .null /// prviate error private var _error: NSError? = nil @@ -140,15 +140,15 @@ public struct JSON { public var object: AnyObject { get { switch self.type { - case .Array: + case .array: return self.rawArray - case .Dictionary: + case .dictionary: return self.rawDictionary - case .String: + case .string: return self.rawString - case .Number: + case .number: return self.rawNumber - case .Bool: + case .bool: return self.rawNumber default: return self.rawNull @@ -159,24 +159,24 @@ public struct JSON { switch newValue { case let number as NSNumber: if number.isBool { - _type = .Bool + _type = .bool } else { - _type = .Number + _type = .number } self.rawNumber = number case let string as String: - _type = .String + _type = .string self.rawString = string case _ as NSNull: - _type = .Null + _type = .null case let array as [AnyObject]: - _type = .Array + _type = .array self.rawArray = array case let dictionary as [String : AnyObject]: - _type = .Dictionary + _type = .dictionary self.rawDictionary = dictionary default: - _type = .Unknown + _type = .unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } @@ -189,229 +189,90 @@ public struct JSON { public var error: NSError? { get { return self._error } } /// The static null json - @available(*, unavailable, renamed="null") + @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } -// MARK: - CollectionType, SequenceType, Indexable -extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable { - - public typealias Generator = JSONGenerator - - public typealias Index = JSONIndex - - public var startIndex: JSON.Index { - switch self.type { - case .Array: - return JSONIndex(arrayIndex: self.rawArray.startIndex) - case .Dictionary: - return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex) - default: - return JSONIndex() - } - } - - public var endIndex: JSON.Index { - switch self.type { - case .Array: - return JSONIndex(arrayIndex: self.rawArray.endIndex) - case .Dictionary: - return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex) - default: - return JSONIndex() - } - } - - public subscript (position: JSON.Index) -> JSON.Generator.Element { - switch self.type { - case .Array: - return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!])) - case .Dictionary: - let (key, value) = self.rawDictionary[position.dictionaryIndex!] - return (key, JSON(value)) - default: - return ("", JSON.null) - } - } - - /// If `type` is `.Array` or `.Dictionary`, return `array.isEmpty` or `dictonary.isEmpty` otherwise return `true`. - public var isEmpty: Bool { - get { - switch self.type { - case .Array: - return self.rawArray.isEmpty - case .Dictionary: - return self.rawDictionary.isEmpty - default: - return true - } - } - } - - /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. - public var count: Int { - switch self.type { - case .Array: - return self.rawArray.count - case .Dictionary: - return self.rawDictionary.count - default: - return 0 - } - } - - public func underestimateCount() -> Int { - switch self.type { - case .Array: - return self.rawArray.underestimateCount() - case .Dictionary: - return self.rawDictionary.underestimateCount() - default: - return 0 - } - } - - /** - If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - - - returns: Return a *generator* over the elements of JSON. - */ - public func generate() -> JSON.Generator { - return JSON.Generator(self) - } -} - -public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable { - - let arrayIndex: Int? - let dictionaryIndex: DictionaryIndex? - - let type: Type - - init(){ - self.arrayIndex = nil - self.dictionaryIndex = nil - self.type = .Unknown - } - - init(arrayIndex: Int) { - self.arrayIndex = arrayIndex - self.dictionaryIndex = nil - self.type = .Array - } - - init(dictionaryIndex: DictionaryIndex) { - self.arrayIndex = nil - self.dictionaryIndex = dictionaryIndex - self.type = .Dictionary - } - - public func successor() -> JSONIndex { - switch self.type { - case .Array: - return JSONIndex(arrayIndex: self.arrayIndex!.successor()) - case .Dictionary: - return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor()) - default: - return JSONIndex() - } - } +public enum JSONIndex:Comparable { + case Array(Int) + case Dictionary(DictionaryIndex) + case Null } public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { - switch (lhs.type, rhs.type) { - case (.Array, .Array): - return lhs.arrayIndex == rhs.arrayIndex - case (.Dictionary, .Dictionary): - return lhs.dictionaryIndex == rhs.dictionaryIndex + switch (lhs, rhs) { + case (.Array(let left), .Array(let right)): + return left == right + case (.Dictionary(let left), .Dictionary(let right)): + return left == right default: return false } } public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { - switch (lhs.type, rhs.type) { - case (.Array, .Array): - return lhs.arrayIndex < rhs.arrayIndex - case (.Dictionary, .Dictionary): - return lhs.dictionaryIndex < rhs.dictionaryIndex + switch (lhs, rhs) { + case (.Array(let left), .Array(let right)): + return left < right + case (.Dictionary(let left), .Dictionary(let right)): + return left < right default: return false } } -public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { - switch (lhs.type, rhs.type) { - case (.Array, .Array): - return lhs.arrayIndex <= rhs.arrayIndex - case (.Dictionary, .Dictionary): - return lhs.dictionaryIndex <= rhs.dictionaryIndex - default: - return false - } -} - -public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { - switch (lhs.type, rhs.type) { - case (.Array, .Array): - return lhs.arrayIndex >= rhs.arrayIndex - case (.Dictionary, .Dictionary): - return lhs.dictionaryIndex >= rhs.dictionaryIndex - default: - return false - } -} -public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool { - switch (lhs.type, rhs.type) { - case (.Array, .Array): - return lhs.arrayIndex > rhs.arrayIndex - case (.Dictionary, .Dictionary): - return lhs.dictionaryIndex > rhs.dictionaryIndex - default: - return false - } -} +extension JSON: Collection{ -public struct JSONGenerator : GeneratorType { + public typealias Index = JSONIndex - public typealias Element = (String, JSON) + public var startIndex: Index{ + switch type { + case .array: + return .Array(rawArray.startIndex) + case .dictionary: + return .Dictionary(dictionaryValue.startIndex) + default: + return .Null + } + } - private let type: Type - private var dictionayGenerate: DictionaryGenerator? - private var arrayGenerate: IndexingGenerator<[AnyObject]>? - private var arrayIndex: Int = 0 + public var endIndex: Index{ + switch type { + case .array: + return .Array(rawArray.endIndex) + case .dictionary: + return .Dictionary(dictionaryValue.endIndex) + default: + return .Null + } + } - init(_ json: JSON) { - self.type = json.type - if type == .Array { - self.arrayGenerate = json.rawArray.generate() - }else { - self.dictionayGenerate = json.rawDictionary.generate() + public func index(after i: Index) -> Index { + switch i { + case .Array(let idx): + return .Array(rawArray.index(after: idx)) + case .Dictionary(let idx): + return .Dictionary(dictionaryValue.index(after: idx)) + default: + return .Null } + } - public mutating func next() -> JSONGenerator.Element? { - switch self.type { - case .Array: - if let o = self.arrayGenerate?.next() { - let i = self.arrayIndex - self.arrayIndex += 1 - return (String(i), JSON(o)) - } else { - return nil - } - case .Dictionary: - if let (k, v): (String, AnyObject) = self.dictionayGenerate?.next() { - return (k, JSON(v)) - } else { - return nil - } + public subscript (position: Index) -> (String, JSON) { + switch position { + case .Array(let idx): + return (String(idx), JSON(self.rawArray[idx])) + case .Dictionary(let idx): + return dictionaryValue[idx] default: - return nil + return ("", JSON.null) } } + + } // MARK: - Subscript @@ -420,8 +281,8 @@ public struct JSONGenerator : GeneratorType { * To mark both String and Int can be used in subscript. */ public enum JSONKey { - case Index(Int) - case Key(String) + case index(Int) + case key(String) } public protocol JSONSubscriptType { @@ -430,13 +291,13 @@ public protocol JSONSubscriptType { extension Int: JSONSubscriptType { public var jsonKey:JSONKey { - return JSONKey.Index(self) + return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey:JSONKey { - return JSONKey.Key(self) + return JSONKey.key(self) } } @@ -445,7 +306,7 @@ extension JSON { /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { - if self.type != .Array { + if self.type != .array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return r @@ -458,7 +319,7 @@ extension JSON { } } set { - if self.type == .Array { + if self.type == .array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } @@ -470,7 +331,7 @@ extension JSON { private subscript(key key: String) -> JSON { get { var r = JSON.null - if self.type == .Dictionary { + if self.type == .dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { @@ -482,7 +343,7 @@ extension JSON { return r } set { - if self.type == .Dictionary && newValue.error == nil { + if self.type == .dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } @@ -492,14 +353,14 @@ extension JSON { private subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { - case .Index(let index): return self[index: index] - case .Key(let key): return self[key: key] + case .index(let index): return self[index: index] + case .key(let key): return self[key: key] } } set { switch sub.jsonKey { - case .Index(let index): self[index: index] = newValue - case .Key(let key): self[key: key] = newValue + case .index(let index): self[index: index] = newValue + case .key(let key): self[key: key] = newValue } } } @@ -528,7 +389,7 @@ extension JSON { case 1: self[sub:path[0]].object = newValue.object default: - var aPath = path; aPath.removeAtIndex(0) + var aPath = path; aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON @@ -625,7 +486,7 @@ extension JSON: Swift.NilLiteralConvertible { extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { - if JSON(rawValue).type == .Unknown { + if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) @@ -636,30 +497,30 @@ extension JSON: Swift.RawRepresentable { return self.object } - public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { - guard NSJSONSerialization.isValidJSONObject(self.object) else { + public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { + guard JSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } - return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) + return try JSONSerialization.data(withJSONObject: self.object, options: opt) } - public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { + public func rawString(_ encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { switch self.type { - case .Array, .Dictionary: + case .array, .dictionary: do { let data = try self.rawData(options: opt) - return NSString(data: data, encoding: encoding) as? String + return String(data: data, encoding: encoding) } catch _ { return nil } - case .String: + case .string: return self.rawString - case .Number: + case .number: return self.rawNumber.stringValue - case .Bool: + case .bool: return self.rawNumber.boolValue.description - case .Null: + case .null: return "null" default: return nil @@ -669,10 +530,10 @@ extension JSON: Swift.RawRepresentable { // MARK: - Printable, DebugPrintable -extension JSON: Swift.Printable, Swift.DebugPrintable { +extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { - if let string = self.rawString(options:.PrettyPrinted) { + if let string = self.rawString(options:.prettyPrinted) { return string } else { return "unknown" @@ -691,7 +552,7 @@ extension JSON { //Optional [JSON] public var array: [JSON]? { get { - if self.type == .Array { + if self.type == .array { return self.rawArray.map{ JSON($0) } } else { return nil @@ -710,7 +571,7 @@ extension JSON { public var arrayObject: [AnyObject]? { get { switch self.type { - case .Array: + case .array: return self.rawArray default: return nil @@ -732,8 +593,9 @@ extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { - if self.type == .Dictionary { - return self.rawDictionary.reduce([String : JSON](minimumCapacity: count)) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in + if self.type == .dictionary { + + return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in var d = dictionary d[element.0] = JSON(element.1) return d @@ -752,7 +614,7 @@ extension JSON { public var dictionaryObject: [String : AnyObject]? { get { switch self.type { - case .Dictionary: + case .dictionary: return self.rawDictionary default: return nil @@ -770,13 +632,13 @@ extension JSON { // MARK: - Bool -extension JSON: Swift.BooleanType { +extension JSON: Swift.Boolean { //Optional bool public var bool: Bool? { get { switch self.type { - case .Bool: + case .bool: return self.rawNumber.boolValue default: return nil @@ -784,7 +646,7 @@ extension JSON: Swift.BooleanType { } set { if let newValue = newValue { - self.object = NSNumber(bool: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -795,14 +657,14 @@ extension JSON: Swift.BooleanType { public var boolValue: Bool { get { switch self.type { - case .Bool, .Number, .String: + case .bool, .number, .string: return self.object.boolValue default: return false } } set { - self.object = NSNumber(bool: newValue) + self.object = NSNumber(value: newValue) } } } @@ -815,7 +677,7 @@ extension JSON { public var string: String? { get { switch self.type { - case .String: + case .string: return self.object as? String default: return nil @@ -834,11 +696,11 @@ extension JSON { public var stringValue: String { get { switch self.type { - case .String: + case .string: return self.object as? String ?? "" - case .Number: + case .number: return self.object.stringValue - case .Bool: + case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" @@ -857,7 +719,7 @@ extension JSON { public var number: NSNumber? { get { switch self.type { - case .Number, .Bool: + case .number, .bool: return self.rawNumber default: return nil @@ -872,16 +734,16 @@ extension JSON { public var numberValue: NSNumber { get { switch self.type { - case .String: + case .string: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber() { // indicates parse error return NSDecimalNumber.zero() } return decimal - case .Number, .Bool: - return self.object as? NSNumber ?? NSNumber(int: 0) + case .number, .bool: + return self.object as? NSNumber ?? NSNumber(value: 0) default: - return NSNumber(double: 0.0) + return NSNumber(value: 0.0) } } set { @@ -896,7 +758,7 @@ extension JSON { public var null: NSNull? { get { switch self.type { - case .Null: + case .null: return self.rawNull default: return nil @@ -918,12 +780,12 @@ extension JSON { extension JSON { //Optional URL - public var URL: NSURL? { + public var URL: Foundation.URL? { get { switch self.type { - case .String: - if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) { - return NSURL(string: encodedString_) + case .string: + if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { + return Foundation.URL(string: encodedString_) } else { return nil } @@ -947,7 +809,7 @@ extension JSON { } set { if let newValue = newValue { - self.object = NSNumber(double: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -959,7 +821,7 @@ extension JSON { return self.numberValue.doubleValue } set { - self.object = NSNumber(double: newValue) + self.object = NSNumber(value: newValue) } } @@ -969,7 +831,7 @@ extension JSON { } set { if let newValue = newValue { - self.object = NSNumber(float: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -981,17 +843,17 @@ extension JSON { return self.numberValue.floatValue } set { - self.object = NSNumber(float: newValue) + self.object = NSNumber(value: newValue) } } public var int: Int? { get { - return self.number?.longValue + return self.number?.intValue } set { if let newValue = newValue { - self.object = NSNumber(integer: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1000,20 +862,20 @@ extension JSON { public var intValue: Int { get { - return self.numberValue.integerValue + return self.numberValue.intValue } set { - self.object = NSNumber(integer: newValue) + self.object = NSNumber(value: newValue) } } public var uInt: UInt? { get { - return self.number?.unsignedLongValue + return self.number?.uintValue } set { if let newValue = newValue { - self.object = NSNumber(unsignedLong: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1022,20 +884,20 @@ extension JSON { public var uIntValue: UInt { get { - return self.numberValue.unsignedLongValue + return self.numberValue.uintValue } set { - self.object = NSNumber(unsignedLong: newValue) + self.object = NSNumber(value: newValue) } } public var int8: Int8? { get { - return self.number?.charValue + return self.number?.int8Value } set { if let newValue = newValue { - self.object = NSNumber(char: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1044,20 +906,20 @@ extension JSON { public var int8Value: Int8 { get { - return self.numberValue.charValue + return self.numberValue.int8Value } set { - self.object = NSNumber(char: newValue) + self.object = NSNumber(value: newValue) } } public var uInt8: UInt8? { get { - return self.number?.unsignedCharValue + return self.number?.uint8Value } set { if let newValue = newValue { - self.object = NSNumber(unsignedChar: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1066,20 +928,20 @@ extension JSON { public var uInt8Value: UInt8 { get { - return self.numberValue.unsignedCharValue + return self.numberValue.uint8Value } set { - self.object = NSNumber(unsignedChar: newValue) + self.object = NSNumber(value: newValue) } } public var int16: Int16? { get { - return self.number?.shortValue + return self.number?.int16Value } set { if let newValue = newValue { - self.object = NSNumber(short: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1088,20 +950,20 @@ extension JSON { public var int16Value: Int16 { get { - return self.numberValue.shortValue + return self.numberValue.int16Value } set { - self.object = NSNumber(short: newValue) + self.object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { - return self.number?.unsignedShortValue + return self.number?.uint16Value } set { if let newValue = newValue { - self.object = NSNumber(unsignedShort: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1110,20 +972,20 @@ extension JSON { public var uInt16Value: UInt16 { get { - return self.numberValue.unsignedShortValue + return self.numberValue.uint16Value } set { - self.object = NSNumber(unsignedShort: newValue) + self.object = NSNumber(value: newValue) } } public var int32: Int32? { get { - return self.number?.intValue + return self.number?.int32Value } set { if let newValue = newValue { - self.object = NSNumber(int: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1132,20 +994,20 @@ extension JSON { public var int32Value: Int32 { get { - return self.numberValue.intValue + return self.numberValue.int32Value } set { - self.object = NSNumber(int: newValue) + self.object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { - return self.number?.unsignedIntValue + return self.number?.uint32Value } set { if let newValue = newValue { - self.object = NSNumber(unsignedInt: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1154,20 +1016,20 @@ extension JSON { public var uInt32Value: UInt32 { get { - return self.numberValue.unsignedIntValue + return self.numberValue.uint32Value } set { - self.object = NSNumber(unsignedInt: newValue) + self.object = NSNumber(value: newValue) } } public var int64: Int64? { get { - return self.number?.longLongValue + return self.number?.int64Value } set { if let newValue = newValue { - self.object = NSNumber(longLong: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1176,20 +1038,20 @@ extension JSON { public var int64Value: Int64 { get { - return self.numberValue.longLongValue + return self.numberValue.int64Value } set { - self.object = NSNumber(longLong: newValue) + self.object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { - return self.number?.unsignedLongLongValue + return self.number?.uint64Value } set { if let newValue = newValue { - self.object = NSNumber(unsignedLongLong: newValue) + self.object = NSNumber(value: newValue) } else { self.object = NSNull() } @@ -1198,10 +1060,10 @@ extension JSON { public var uInt64Value: UInt64 { get { - return self.numberValue.unsignedLongLongValue + return self.numberValue.uint64Value } set { - self.object = NSNumber(unsignedLongLong: newValue) + self.object = NSNumber(value: newValue) } } } @@ -1212,17 +1074,17 @@ extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.Number, .Number): + case (.number, .number): return lhs.rawNumber == rhs.rawNumber - case (.String, .String): + case (.string, .string): return lhs.rawString == rhs.rawString - case (.Bool, .Bool): + case (.bool, .bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue - case (.Array, .Array): + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.Dictionary, .Dictionary): + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.Null, .Null): + case (.null, .null): return true default: return false @@ -1232,17 +1094,17 @@ public func ==(lhs: JSON, rhs: JSON) -> Bool { public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.Number, .Number): + case (.number, .number): return lhs.rawNumber <= rhs.rawNumber - case (.String, .String): + case (.string, .string): return lhs.rawString <= rhs.rawString - case (.Bool, .Bool): + case (.bool, .bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue - case (.Array, .Array): + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.Dictionary, .Dictionary): + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.Null, .Null): + case (.null, .null): return true default: return false @@ -1252,17 +1114,17 @@ public func <=(lhs: JSON, rhs: JSON) -> Bool { public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.Number, .Number): + case (.number, .number): return lhs.rawNumber >= rhs.rawNumber - case (.String, .String): + case (.string, .string): return lhs.rawString >= rhs.rawString - case (.Bool, .Bool): + case (.bool, .bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue - case (.Array, .Array): + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.Dictionary, .Dictionary): + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.Null, .Null): + case (.null, .null): return true default: return false @@ -1272,9 +1134,9 @@ public func >=(lhs: JSON, rhs: JSON) -> Bool { public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.Number, .Number): + case (.number, .number): return lhs.rawNumber > rhs.rawNumber - case (.String, .String): + case (.string, .string): return lhs.rawString > rhs.rawString default: return false @@ -1284,28 +1146,28 @@ public func >(lhs: JSON, rhs: JSON) -> Bool { public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.Number, .Number): + case (.number, .number): return lhs.rawNumber < rhs.rawNumber - case (.String, .String): + case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } -private let trueNumber = NSNumber(bool: true) -private let falseNumber = NSNumber(bool: false) -private let trueObjCType = String.fromCString(trueNumber.objCType) -private let falseObjCType = String.fromCString(falseNumber.objCType) +private let trueNumber = NSNumber(value: true) +private let falseNumber = NSNumber(value: false) +private let trueObjCType = String(cString: trueNumber.objCType) +private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { - let objCType = String.fromCString(self.objCType) - if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) - || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ + let objCType = String(cString: self.objCType) + if (self.compare(trueNumber) == ComparisonResult.orderedSame && objCType == trueObjCType) + || (self.compare(falseNumber) == ComparisonResult.orderedSame && objCType == falseObjCType){ return true } else { return false @@ -1321,7 +1183,7 @@ func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { case (true, false): return false default: - return lhs.compare(rhs) == NSComparisonResult.OrderedSame + return lhs.compare(rhs) == ComparisonResult.orderedSame } } @@ -1337,7 +1199,7 @@ func <(lhs: NSNumber, rhs: NSNumber) -> Bool { case (true, false): return false default: - return lhs.compare(rhs) == NSComparisonResult.OrderedAscending + return lhs.compare(rhs) == ComparisonResult.orderedAscending } } @@ -1349,7 +1211,7 @@ func >(lhs: NSNumber, rhs: NSNumber) -> Bool { case (true, false): return false default: - return lhs.compare(rhs) == NSComparisonResult.OrderedDescending + return lhs.compare(rhs) == ComparisonResult.orderedDescending } } @@ -1361,7 +1223,7 @@ func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { case (true, false): return false default: - return lhs.compare(rhs) != NSComparisonResult.OrderedDescending + return lhs.compare(rhs) != ComparisonResult.orderedDescending } } @@ -1373,6 +1235,6 @@ func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { case (true, false): return false default: - return lhs.compare(rhs) != NSComparisonResult.OrderedAscending + return lhs.compare(rhs) != ComparisonResult.orderedAscending } } diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index f3628d27..10897c87 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -422,13 +422,15 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0710; - LastUpgradeCheck = 0700; + LastUpgradeCheck = 0800; TargetAttributes = { 2E4FEFDA19575BE100351305 = { CreatedOnToolsVersion = 6.0; + LastSwiftMigration = 0800; }; 2E4FEFE519575BE100351305 = { CreatedOnToolsVersion = 6.0; + LastSwiftMigration = 0800; TestTargetID = 2E4FEFDA19575BE100351305; }; 9C7DFC5A1A9102BD005AA3F7 = { @@ -658,6 +660,7 @@ ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = fast; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", @@ -670,7 +673,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; MACOSX_DEPLOYMENT_TARGET = 10.9; METAL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; @@ -705,6 +708,7 @@ ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = fast; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; @@ -712,7 +716,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; MACOSX_DEPLOYMENT_TARGET = 10.9; METAL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; @@ -742,6 +746,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -763,6 +768,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -779,6 +785,7 @@ METAL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -791,6 +798,7 @@ METAL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Release; }; diff --git a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme index 1441778e..6d7a6f62 100644 --- a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme +++ b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme @@ -1,6 +1,6 @@ + shouldUseLaunchSchemeArgsEnv = "YES"> @@ -66,11 +66,11 @@ + shouldUseLaunchSchemeArgsEnv = "YES"> @@ -66,11 +66,11 @@ diff --git a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON watchOS.xcscheme b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON watchOS.xcscheme index 7dacc905..d760fb2b 100644 --- a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON watchOS.xcscheme +++ b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON watchOS.xcscheme @@ -1,6 +1,6 @@ = -988343) - let jsonL3:JSON = JSON(NSNumber(double:87621.12345678)) - let jsonR3:JSON = JSON(NSNumber(double:87621.12345678)) + let jsonL3:JSON = JSON(NSNumber(value:87621.12345678)) + let jsonR3:JSON = JSON(NSNumber(value:87621.12345678)) XCTAssertGreaterThanOrEqual(jsonL3, jsonR3) XCTAssertTrue(jsonR3 >= 0.3232) } @@ -88,8 +88,8 @@ class ComparableTests: XCTestCase { XCTAssertLessThanOrEqual(jsonR2, jsonL2) XCTAssertFalse(9348343 <= jsonR2) - let jsonL3:JSON = JSON(NSNumber(double:87621.12345678)) - let jsonR3:JSON = JSON(NSNumber(double:87621.12345678)) + let jsonL3:JSON = JSON(NSNumber(value:87621.12345678)) + let jsonR3:JSON = JSON(NSNumber(value:87621.12345678)) XCTAssertLessThanOrEqual(jsonR3, jsonL3) XCTAssertTrue(87621.12345678 <= jsonR3) } @@ -105,8 +105,8 @@ class ComparableTests: XCTestCase { XCTAssertGreaterThan(jsonL2, jsonR2) XCTAssertFalse(jsonR2 > 877434) - let jsonL3:JSON = JSON(NSNumber(double:87621.12345678)) - let jsonR3:JSON = JSON(NSNumber(double:87621.1234567)) + let jsonL3:JSON = JSON(NSNumber(value:87621.12345678)) + let jsonR3:JSON = JSON(NSNumber(value:87621.1234567)) XCTAssertGreaterThan(jsonL3, jsonR3) XCTAssertFalse(-7799 > jsonR3) } @@ -122,8 +122,8 @@ class ComparableTests: XCTestCase { XCTAssertLessThan(jsonR2, jsonL2) XCTAssertTrue(jsonR2 < 877434) - let jsonL3:JSON = JSON(NSNumber(double:87621.12345678)) - let jsonR3:JSON = JSON(NSNumber(double:87621.1234567)) + let jsonL3:JSON = JSON(NSNumber(value:87621.12345678)) + let jsonR3:JSON = JSON(NSNumber(value:87621.1234567)) XCTAssertLessThan(jsonR3, jsonL3) XCTAssertTrue(-7799 < jsonR3) } diff --git a/Tests/NumberTests.swift b/Tests/NumberTests.swift index 6b7b954d..8e19517b 100644 --- a/Tests/NumberTests.swift +++ b/Tests/NumberTests.swift @@ -26,7 +26,7 @@ class NumberTests: XCTestCase { func testNumber() { //getter - var json = JSON(NSNumber(double: 9876543210.123456789)) + var json = JSON(NSNumber(value: 9876543210.123456789)) XCTAssertEqual(json.number!, 9876543210.123456789) XCTAssertEqual(json.numberValue, 9876543210.123456789) XCTAssertEqual(json.stringValue, "9876543210.123457") @@ -39,7 +39,7 @@ class NumberTests: XCTestCase { XCTAssertEqual(json.numberValue.description, "1000000000000000000000000000") //setter - json.number = NSNumber(double: 123456789.0987654321) + json.number = NSNumber(value: 123456789.0987654321) XCTAssertEqual(json.number!, 123456789.0987654321) XCTAssertEqual(json.numberValue, 123456789.0987654321) @@ -106,22 +106,22 @@ class NumberTests: XCTestCase { XCTAssertEqual(json.numberValue, 54321.12345) XCTAssertEqual(json.stringValue, "54321.12345") - json.float = 23231.65 + json.double = 23231.65 XCTAssertTrue(json.float! == 23231.65) XCTAssertTrue(json.floatValue == 23231.65) - XCTAssertEqual(json.numberValue, NSNumber(float:23231.65)) + XCTAssertEqual(json.numberValue, NSNumber(value:23231.65)) - json.floatValue = -98766.23 + json.double = -98766.23 XCTAssertEqual(json.float!, -98766.23) XCTAssertEqual(json.floatValue, -98766.23) - XCTAssertEqual(json.numberValue, NSNumber(float:-98766.23)) + XCTAssertEqual(json.numberValue, NSNumber(value:-98766.23)) } func testInt() { var json = JSON(123456789) XCTAssertEqual(json.int!, 123456789) XCTAssertEqual(json.intValue, 123456789) - XCTAssertEqual(json.numberValue, NSNumber(integer: 123456789)) + XCTAssertEqual(json.numberValue, NSNumber(value: 123456789)) XCTAssertEqual(json.stringValue, "123456789") json.int = nil @@ -134,19 +134,19 @@ class NumberTests: XCTestCase { json.intValue = 76543 XCTAssertEqual(json.int!, 76543) XCTAssertEqual(json.intValue, 76543) - XCTAssertEqual(json.numberValue, NSNumber(integer: 76543)) + XCTAssertEqual(json.numberValue, NSNumber(value: 76543)) json.intValue = 98765421 XCTAssertEqual(json.int!, 98765421) XCTAssertEqual(json.intValue, 98765421) - XCTAssertEqual(json.numberValue, NSNumber(integer: 98765421)) + XCTAssertEqual(json.numberValue, NSNumber(value: 98765421)) } func testUInt() { var json = JSON(123456789) XCTAssertTrue(json.uInt! == 123456789) XCTAssertTrue(json.uIntValue == 123456789) - XCTAssertEqual(json.numberValue, NSNumber(unsignedInteger: 123456789)) + XCTAssertEqual(json.numberValue, NSNumber(value: 123456789)) XCTAssertEqual(json.stringValue, "123456789") json.uInt = nil @@ -159,35 +159,35 @@ class NumberTests: XCTestCase { json.uIntValue = 76543 XCTAssertTrue(json.uInt! == 76543) XCTAssertTrue(json.uIntValue == 76543) - XCTAssertEqual(json.numberValue, NSNumber(unsignedInteger: 76543)) + XCTAssertEqual(json.numberValue, NSNumber(value: 76543)) json.uIntValue = 98765421 XCTAssertTrue(json.uInt! == 98765421) XCTAssertTrue(json.uIntValue == 98765421) - XCTAssertEqual(json.numberValue, NSNumber(unsignedInteger: 98765421)) + XCTAssertEqual(json.numberValue, NSNumber(value: 98765421)) } func testInt8() { - let n127 = NSNumber(char: 127) + let n127 = NSNumber(value: 127) var json = JSON(n127) - XCTAssertTrue(json.int8! == n127.charValue) - XCTAssertTrue(json.int8Value == n127.charValue) + XCTAssertTrue(json.int8! == n127.int8Value) + XCTAssertTrue(json.int8Value == n127.int8Value) XCTAssertTrue(json.number! == n127) XCTAssertEqual(json.numberValue, n127) XCTAssertEqual(json.stringValue, "127") - let nm128 = NSNumber(char: -128) - json.int8Value = nm128.charValue - XCTAssertTrue(json.int8! == nm128.charValue) - XCTAssertTrue(json.int8Value == nm128.charValue) + let nm128 = NSNumber(value: -128) + json.int8Value = nm128.int8Value + XCTAssertTrue(json.int8! == nm128.int8Value) + XCTAssertTrue(json.int8Value == nm128.int8Value) XCTAssertTrue(json.number! == nm128) XCTAssertEqual(json.numberValue, nm128) XCTAssertEqual(json.stringValue, "-128") - let n0 = NSNumber(char: 0 as Int8) - json.int8Value = n0.charValue - XCTAssertTrue(json.int8! == n0.charValue) - XCTAssertTrue(json.int8Value == n0.charValue) + let n0 = NSNumber(value: 0 as Int8) + json.int8Value = n0.int8Value + XCTAssertTrue(json.int8! == n0.int8Value) + XCTAssertTrue(json.int8Value == n0.int8Value) print(json.number) XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) @@ -198,10 +198,10 @@ class NumberTests: XCTestCase { #endif - let n1 = NSNumber(char: 1 as Int8) - json.int8Value = n1.charValue - XCTAssertTrue(json.int8! == n1.charValue) - XCTAssertTrue(json.int8Value == n1.charValue) + let n1 = NSNumber(value: 1 as Int8) + json.int8Value = n1.int8Value + XCTAssertTrue(json.int8! == n1.int8Value) + XCTAssertTrue(json.int8Value == n1.int8Value) XCTAssertTrue(json.number! == n1) XCTAssertEqual(json.numberValue, n1) #if (arch(x86_64) || arch(arm64)) @@ -212,34 +212,34 @@ class NumberTests: XCTestCase { } func testUInt8() { - let n255 = NSNumber(unsignedChar: 255) + let n255 = NSNumber(value: 255) var json = JSON(n255) - XCTAssertTrue(json.uInt8! == n255.unsignedCharValue) - XCTAssertTrue(json.uInt8Value == n255.unsignedCharValue) + XCTAssertTrue(json.uInt8! == n255.uint8Value) + XCTAssertTrue(json.uInt8Value == n255.uint8Value) XCTAssertTrue(json.number! == n255) XCTAssertEqual(json.numberValue, n255) XCTAssertEqual(json.stringValue, "255") - let nm2 = NSNumber(unsignedChar: 2) - json.uInt8Value = nm2.unsignedCharValue - XCTAssertTrue(json.uInt8! == nm2.unsignedCharValue) - XCTAssertTrue(json.uInt8Value == nm2.unsignedCharValue) + let nm2 = NSNumber(value: 2) + json.uInt8Value = nm2.uint8Value + XCTAssertTrue(json.uInt8! == nm2.uint8Value) + XCTAssertTrue(json.uInt8Value == nm2.uint8Value) XCTAssertTrue(json.number! == nm2) XCTAssertEqual(json.numberValue, nm2) XCTAssertEqual(json.stringValue, "2") - let nm0 = NSNumber(unsignedChar: 0) - json.uInt8Value = nm0.unsignedCharValue - XCTAssertTrue(json.uInt8! == nm0.unsignedCharValue) - XCTAssertTrue(json.uInt8Value == nm0.unsignedCharValue) + let nm0 = NSNumber(value: 0) + json.uInt8Value = nm0.uint8Value + XCTAssertTrue(json.uInt8! == nm0.uint8Value) + XCTAssertTrue(json.uInt8Value == nm0.uint8Value) XCTAssertTrue(json.number! == nm0) XCTAssertEqual(json.numberValue, nm0) XCTAssertEqual(json.stringValue, "0") - let nm1 = NSNumber(unsignedChar: 1) - json.uInt8 = nm1.unsignedCharValue - XCTAssertTrue(json.uInt8! == nm1.unsignedCharValue) - XCTAssertTrue(json.uInt8Value == nm1.unsignedCharValue) + let nm1 = NSNumber(value: 1) + json.uInt8 = nm1.uint8Value + XCTAssertTrue(json.uInt8! == nm1.uint8Value) + XCTAssertTrue(json.uInt8Value == nm1.uint8Value) XCTAssertTrue(json.number! == nm1) XCTAssertEqual(json.numberValue, nm1) XCTAssertEqual(json.stringValue, "1") @@ -247,35 +247,35 @@ class NumberTests: XCTestCase { func testInt16() { - let n32767 = NSNumber(short: 32767) + let n32767 = NSNumber(value: 32767) var json = JSON(n32767) - XCTAssertTrue(json.int16! == n32767.shortValue) - XCTAssertTrue(json.int16Value == n32767.shortValue) + XCTAssertTrue(json.int16! == n32767.int16Value) + XCTAssertTrue(json.int16Value == n32767.int16Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") - let nm32768 = NSNumber(short: -32768) - json.int16Value = nm32768.shortValue - XCTAssertTrue(json.int16! == nm32768.shortValue) - XCTAssertTrue(json.int16Value == nm32768.shortValue) + let nm32768 = NSNumber(value: -32768) + json.int16Value = nm32768.int16Value + XCTAssertTrue(json.int16! == nm32768.int16Value) + XCTAssertTrue(json.int16Value == nm32768.int16Value) XCTAssertTrue(json.number! == nm32768) XCTAssertEqual(json.numberValue, nm32768) XCTAssertEqual(json.stringValue, "-32768") - let n0 = NSNumber(short: 0) - json.int16Value = n0.shortValue - XCTAssertTrue(json.int16! == n0.shortValue) - XCTAssertTrue(json.int16Value == n0.shortValue) + let n0 = NSNumber(value: 0) + json.int16Value = n0.int16Value + XCTAssertTrue(json.int16! == n0.int16Value) + XCTAssertTrue(json.int16Value == n0.int16Value) print(json.number) XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") - let n1 = NSNumber(short: 1) - json.int16 = n1.shortValue - XCTAssertTrue(json.int16! == n1.shortValue) - XCTAssertTrue(json.int16Value == n1.shortValue) + let n1 = NSNumber(value: 1) + json.int16 = n1.int16Value + XCTAssertTrue(json.int16! == n1.int16Value) + XCTAssertTrue(json.int16Value == n1.int16Value) XCTAssertTrue(json.number! == n1) XCTAssertEqual(json.numberValue, n1) XCTAssertEqual(json.stringValue, "1") @@ -283,114 +283,114 @@ class NumberTests: XCTestCase { func testUInt16() { - let n65535 = NSNumber(unsignedInteger: 65535) + let n65535 = NSNumber(value: 65535) var json = JSON(n65535) - XCTAssertTrue(json.uInt16! == n65535.unsignedShortValue) - XCTAssertTrue(json.uInt16Value == n65535.unsignedShortValue) + XCTAssertTrue(json.uInt16! == n65535.uint16Value) + XCTAssertTrue(json.uInt16Value == n65535.uint16Value) XCTAssertTrue(json.number! == n65535) XCTAssertEqual(json.numberValue, n65535) XCTAssertEqual(json.stringValue, "65535") - let n32767 = NSNumber(unsignedInteger: 32767) - json.uInt16 = n32767.unsignedShortValue - XCTAssertTrue(json.uInt16! == n32767.unsignedShortValue) - XCTAssertTrue(json.uInt16Value == n32767.unsignedShortValue) + let n32767 = NSNumber(value: 32767) + json.uInt16 = n32767.uint16Value + XCTAssertTrue(json.uInt16! == n32767.uint16Value) + XCTAssertTrue(json.uInt16Value == n32767.uint16Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") } func testInt32() { - let n2147483647 = NSNumber(int: 2147483647) + let n2147483647 = NSNumber(value: 2147483647) var json = JSON(n2147483647) - XCTAssertTrue(json.int32! == n2147483647.intValue) - XCTAssertTrue(json.int32Value == n2147483647.intValue) + XCTAssertTrue(json.int32! == n2147483647.int32Value) + XCTAssertTrue(json.int32Value == n2147483647.int32Value) XCTAssertTrue(json.number! == n2147483647) XCTAssertEqual(json.numberValue, n2147483647) XCTAssertEqual(json.stringValue, "2147483647") - let n32767 = NSNumber(int: 32767) - json.int32 = n32767.intValue - XCTAssertTrue(json.int32! == n32767.intValue) - XCTAssertTrue(json.int32Value == n32767.intValue) + let n32767 = NSNumber(value: 32767) + json.int32 = n32767.int32Value + XCTAssertTrue(json.int32! == n32767.int32Value) + XCTAssertTrue(json.int32Value == n32767.int32Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") - let nm2147483648 = NSNumber(int: -2147483648) - json.int32Value = nm2147483648.intValue - XCTAssertTrue(json.int32! == nm2147483648.intValue) - XCTAssertTrue(json.int32Value == nm2147483648.intValue) + let nm2147483648 = NSNumber(value: -2147483648) + json.int32Value = nm2147483648.int32Value + XCTAssertTrue(json.int32! == nm2147483648.int32Value) + XCTAssertTrue(json.int32Value == nm2147483648.int32Value) XCTAssertTrue(json.number! == nm2147483648) XCTAssertEqual(json.numberValue, nm2147483648) XCTAssertEqual(json.stringValue, "-2147483648") } func testUInt32() { - let n2147483648 = NSNumber(unsignedInt: 2147483648) + let n2147483648 = NSNumber(value: 2147483648) var json = JSON(n2147483648) - XCTAssertTrue(json.uInt32! == n2147483648.unsignedIntValue) - XCTAssertTrue(json.uInt32Value == n2147483648.unsignedIntValue) + XCTAssertTrue(json.uInt32! == n2147483648.uint32Value) + XCTAssertTrue(json.uInt32Value == n2147483648.uint32Value) XCTAssertTrue(json.number! == n2147483648) XCTAssertEqual(json.numberValue, n2147483648) XCTAssertEqual(json.stringValue, "2147483648") - let n32767 = NSNumber(unsignedInt: 32767) - json.uInt32 = n32767.unsignedIntValue - XCTAssertTrue(json.uInt32! == n32767.unsignedIntValue) - XCTAssertTrue(json.uInt32Value == n32767.unsignedIntValue) + let n32767 = NSNumber(value: 32767) + json.uInt32 = n32767.uint32Value + XCTAssertTrue(json.uInt32! == n32767.uint32Value) + XCTAssertTrue(json.uInt32Value == n32767.uint32Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") - let n0 = NSNumber(unsignedInt: 0) - json.uInt32Value = n0.unsignedIntValue - XCTAssertTrue(json.uInt32! == n0.unsignedIntValue) - XCTAssertTrue(json.uInt32Value == n0.unsignedIntValue) + let n0 = NSNumber(value: 0) + json.uInt32Value = n0.uint32Value + XCTAssertTrue(json.uInt32! == n0.uint32Value) + XCTAssertTrue(json.uInt32Value == n0.uint32Value) XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") } func testInt64() { - let int64Max = NSNumber(longLong: INT64_MAX) + let int64Max = NSNumber(value: INT64_MAX) var json = JSON(int64Max) - XCTAssertTrue(json.int64! == int64Max.longLongValue) - XCTAssertTrue(json.int64Value == int64Max.longLongValue) + XCTAssertTrue(json.int64! == int64Max.int64Value) + XCTAssertTrue(json.int64Value == int64Max.int64Value) XCTAssertTrue(json.number! == int64Max) XCTAssertEqual(json.numberValue, int64Max) XCTAssertEqual(json.stringValue, int64Max.stringValue) - let n32767 = NSNumber(longLong: 32767) - json.int64 = n32767.longLongValue - XCTAssertTrue(json.int64! == n32767.longLongValue) - XCTAssertTrue(json.int64Value == n32767.longLongValue) + let n32767 = NSNumber(value: 32767) + json.int64 = n32767.int64Value + XCTAssertTrue(json.int64! == n32767.int64Value) + XCTAssertTrue(json.int64Value == n32767.int64Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") - let int64Min = NSNumber(longLong: (INT64_MAX-1) * -1) - json.int64Value = int64Min.longLongValue - XCTAssertTrue(json.int64! == int64Min.longLongValue) - XCTAssertTrue(json.int64Value == int64Min.longLongValue) + let int64Min = NSNumber(value: (INT64_MAX-1) * -1) + json.int64Value = int64Min.int64Value + XCTAssertTrue(json.int64! == int64Min.int64Value) + XCTAssertTrue(json.int64Value == int64Min.int64Value) XCTAssertTrue(json.number! == int64Min) XCTAssertEqual(json.numberValue, int64Min) XCTAssertEqual(json.stringValue, int64Min.stringValue) } func testUInt64() { - let uInt64Max = NSNumber(unsignedLongLong: UINT64_MAX) + let uInt64Max = NSNumber(value: UINT64_MAX) var json = JSON(uInt64Max) - XCTAssertTrue(json.uInt64! == uInt64Max.unsignedLongLongValue) - XCTAssertTrue(json.uInt64Value == uInt64Max.unsignedLongLongValue) + XCTAssertTrue(json.uInt64! == uInt64Max.uint64Value) + XCTAssertTrue(json.uInt64Value == uInt64Max.uint64Value) XCTAssertTrue(json.number! == uInt64Max) XCTAssertEqual(json.numberValue, uInt64Max) XCTAssertEqual(json.stringValue, uInt64Max.stringValue) - let n32767 = NSNumber(longLong: 32767) - json.int64 = n32767.longLongValue - XCTAssertTrue(json.int64! == n32767.longLongValue) - XCTAssertTrue(json.int64Value == n32767.longLongValue) + let n32767 = NSNumber(value: 32767) + json.int64 = n32767.int64Value + XCTAssertTrue(json.int64! == n32767.int64Value) + XCTAssertTrue(json.int64Value == n32767.int64Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") diff --git a/Tests/PerformanceTests.swift b/Tests/PerformanceTests.swift index c7cd7450..18a10ea1 100644 --- a/Tests/PerformanceTests.swift +++ b/Tests/PerformanceTests.swift @@ -25,13 +25,13 @@ import SwiftyJSON class PerformanceTests: XCTestCase { - var testData: NSData! + var testData: Data! override func setUp() { super.setUp() - if let file = NSBundle(forClass:PerformanceTests.self).pathForResource("Tests", ofType: "json") { - self.testData = NSData(contentsOfFile: file) + if let file = Bundle(for:PerformanceTests.self).pathForResource("Tests", ofType: "json") { + self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { XCTFail("Can't find the test JSON file") } @@ -43,7 +43,7 @@ class PerformanceTests: XCTestCase { } func testInitPerformance() { - self.measureBlock() { + self.measure() { for _ in 1...100 { let json = JSON(data:self.testData) XCTAssertTrue(json != JSON.null) @@ -53,7 +53,7 @@ class PerformanceTests: XCTestCase { func testObjectMethodPerformance() { var json = JSON(data:self.testData) - self.measureBlock() { + self.measure() { for _ in 1...100 { let object:AnyObject? = json.object XCTAssertTrue(object != nil) @@ -63,7 +63,7 @@ class PerformanceTests: XCTestCase { func testArrayMethodPerformance() { let json = JSON(data:self.testData) - self.measureBlock() { + self.measure() { for _ in 1...100 { autoreleasepool{ let array = json.array @@ -75,7 +75,7 @@ class PerformanceTests: XCTestCase { func testDictionaryMethodPerformance() { let json = JSON(data:testData)[0] - self.measureBlock() { + self.measure() { for _ in 1...100 { autoreleasepool{ let dictionary = json.dictionary @@ -87,7 +87,7 @@ class PerformanceTests: XCTestCase { func testRawStringMethodPerformance() { let json = JSON(data:testData) - self.measureBlock() { + self.measure() { for _ in 1...100 { autoreleasepool{ let string = json.rawString() diff --git a/Tests/PrintableTests.swift b/Tests/PrintableTests.swift index 2a4203d7..72448288 100644 --- a/Tests/PrintableTests.swift +++ b/Tests/PrintableTests.swift @@ -56,20 +56,20 @@ class PrintableTests: XCTestCase { func testArray() { let json:JSON = [1,2,"4",5,"6"] - var description = json.description.stringByReplacingOccurrencesOfString("\n", withString: "") - description = description.stringByReplacingOccurrencesOfString(" ", withString: "") + var description = json.description.replacingOccurrences(of: "\n", with: "") + description = description.replacingOccurrences(of: " ", with: "") XCTAssertEqual(description, "[1,2,\"4\",5,\"6\"]") - XCTAssertTrue(json.description.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0) - XCTAssertTrue(json.debugDescription.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0) + XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) + XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0) } func testDictionary() { let json:JSON = ["1":2,"2":"two", "3":3] - var debugDescription = json.debugDescription.stringByReplacingOccurrencesOfString("\n", withString: "") - debugDescription = debugDescription.stringByReplacingOccurrencesOfString(" ", withString: "") - XCTAssertTrue(json.description.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0) - XCTAssertTrue(debugDescription.rangeOfString("\"1\":2", options: NSStringCompareOptions.CaseInsensitiveSearch) != nil) - XCTAssertTrue(debugDescription.rangeOfString("\"2\":\"two\"", options: NSStringCompareOptions.CaseInsensitiveSearch) != nil) - XCTAssertTrue(debugDescription.rangeOfString("\"3\":3", options: NSStringCompareOptions.CaseInsensitiveSearch) != nil) + var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") + debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") + XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) + XCTAssertTrue(debugDescription.range(of: "\"1\":2", options: NSString.CompareOptions.caseInsensitiveSearch) != nil) + XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: NSString.CompareOptions.caseInsensitiveSearch) != nil) + XCTAssertTrue(debugDescription.range(of: "\"3\":3", options: NSString.CompareOptions.caseInsensitiveSearch) != nil) } } diff --git a/Tests/RawRepresentableTests.swift b/Tests/RawRepresentableTests.swift index 149246db..e9412481 100644 --- a/Tests/RawRepresentableTests.swift +++ b/Tests/RawRepresentableTests.swift @@ -54,13 +54,13 @@ class RawRepresentableTests: XCTestCase { XCTAssertEqual(objectTrue as? Int, 1) XCTAssertEqual(objectTrue as? Double, 1.0) XCTAssertEqual(objectTrue as? Bool, true) - XCTAssertEqual(objectTrue as? NSNumber, NSNumber(bool: true)) + XCTAssertEqual(objectTrue as? NSNumber, NSNumber(value: true)) let objectFalse: AnyObject = jsonFalse.rawValue XCTAssertEqual(objectFalse as? Int, 0) XCTAssertEqual(objectFalse as? Double, 0.0) XCTAssertEqual(objectFalse as? Bool, false) - XCTAssertEqual(objectFalse as? NSNumber, NSNumber(bool: false)) + XCTAssertEqual(objectFalse as? NSNumber, NSNumber(value: false)) } func testString() { @@ -72,7 +72,7 @@ class RawRepresentableTests: XCTestCase { XCTAssertTrue(json.dictionary == nil) XCTAssertTrue(json.null == nil) XCTAssertTrue(json.error == nil) - XCTAssertTrue(json.type == .String) + XCTAssertTrue(json.type == .string) XCTAssertEqual(json.object as? String, string) } else { XCTFail("Should not run into here") diff --git a/Tests/RawTests.swift b/Tests/RawTests.swift index 86669a66..0799be36 100644 --- a/Tests/RawTests.swift +++ b/Tests/RawTests.swift @@ -27,9 +27,9 @@ class RawTests: XCTestCase { func testRawData() { let json: JSON = ["somekey" : "some string value"] - let expectedRawData = "{\"somekey\":\"some string value\"}".dataUsingEncoding(NSUTF8StringEncoding) + let expectedRawData = "{\"somekey\":\"some string value\"}".data(using: String.Encoding.utf8) do { - let data: NSData = try json.rawData() + let data: Data = try json.rawData() XCTAssertEqual(expectedRawData, data) } catch _ { XCTFail() @@ -47,7 +47,7 @@ class RawTests: XCTestCase { func testArray() { let json:JSON = [1, "2", 3.12, NSNull(), true, ["name": "Jack"]] - let data: NSData? + let data: Data? do { data = try json.rawData() } catch _ { @@ -55,13 +55,13 @@ class RawTests: XCTestCase { } let string = json.rawString() XCTAssertTrue (data != nil) - XCTAssertTrue (string!.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0) + XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0) print(string!) } func testDictionary() { let json:JSON = ["number":111111.23456789, "name":"Jack", "list":[1,2,3,4], "bool":false, "null":NSNull()] - let data: NSData? + let data: Data? do { data = try json.rawData() } catch _ { @@ -69,7 +69,7 @@ class RawTests: XCTestCase { } let string = json.rawString() XCTAssertTrue (data != nil) - XCTAssertTrue (string!.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0) + XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0) print(string!) } diff --git a/Tests/SequenceTypeTests.swift b/Tests/SequenceTypeTests.swift index b3ea4b77..467231f6 100644 --- a/Tests/SequenceTypeTests.swift +++ b/Tests/SequenceTypeTests.swift @@ -27,8 +27,8 @@ import SwiftyJSON class SequenceTypeTests: XCTestCase { func testJSONFile() { - if let file = NSBundle(forClass:BaseTests.self).pathForResource("Tests", ofType: "json") { - let testData = NSData(contentsOfFile: file) + if let file = Bundle(for:BaseTests.self).pathForResource("Tests", ofType: "json") { + let testData = try? Data(contentsOf: URL(fileURLWithPath: file)) let json = JSON(data:testData!) for (index, sub) in json { switch (index as NSString).integerValue { @@ -201,7 +201,7 @@ class SequenceTypeTests: XCTestCase { } func testDictionaryAllArray() { - var json:JSON = JSON (["Number":[NSNumber(integer:1),NSNumber(double:2.123456),NSNumber(int:123456789)], "String":["aa","bbb","cccc"], "Mix":[true, "766", NSNull(), 655231.9823]]) + var json:JSON = JSON (["Number":[NSNumber(value:1),NSNumber(value:2.123456),NSNumber(value:123456789)], "String":["aa","bbb","cccc"], "Mix":[true, "766", NSNull(), 655231.9823]]) XCTAssertEqual(json.count, 3) diff --git a/Tests/StringTests.swift b/Tests/StringTests.swift index 229349a9..8e720be4 100644 --- a/Tests/StringTests.swift +++ b/Tests/StringTests.swift @@ -38,14 +38,14 @@ class StringTests: XCTestCase { func testURL() { let json = JSON("http://github.com") - XCTAssertEqual(json.URL!, NSURL(string:"http://github.com")!) + XCTAssertEqual(json.URL!, URL(string:"http://github.com")!) } func testURLPercentEscapes() { let emDash = "\\u2014" let urlString = "http://examble.com/unencoded" + emDash + "string" - let encodedURLString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) + let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) let json = JSON(urlString) - XCTAssertEqual(json.URL!, NSURL(string: encodedURLString!)!, "Wrong unpacked ") + XCTAssertEqual(json.URL!, URL(string: encodedURLString!)!, "Wrong unpacked ") } } diff --git a/Tests/SubscriptTests.swift b/Tests/SubscriptTests.swift index c5803664..bdbd821a 100644 --- a/Tests/SubscriptTests.swift +++ b/Tests/SubscriptTests.swift @@ -161,7 +161,7 @@ class SubscriptTests: XCTestCase { func testDictionaryAllArray() { //Swift bug: [1, 2.01,3.09] is convert to [1, 2, 3] (Array) - let json:JSON = JSON ([[NSNumber(integer:1),NSNumber(double:2.123456),NSNumber(int:123456789)], ["aa","bbb","cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) + let json:JSON = JSON ([[NSNumber(value:1),NSNumber(value:2.123456),NSNumber(value:123456789)], ["aa","bbb","cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) XCTAssertTrue(json[0] == [1,2.123456,123456789]) XCTAssertEqual(json[0][1].double!, 2.123456) XCTAssertTrue(json[0][2] == 123456789) @@ -178,7 +178,7 @@ class SubscriptTests: XCTestCase { } func testOutOfBounds() { - let json:JSON = JSON ([[NSNumber(integer:1),NSNumber(double:2.123456),NSNumber(int:123456789)], ["aa","bbb","cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) + let json:JSON = JSON ([[NSNumber(value:1),NSNumber(value:2.123456),NSNumber(value:123456789)], ["aa","bbb","cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) XCTAssertEqual(json[9], JSON.null) XCTAssertEqual(json[-2].error!.code, ErrorIndexOutOfBounds) XCTAssertEqual(json[6].error!.code, ErrorIndexOutOfBounds) From f2c0c962cdf353a4831c8ce457aed8343ed898e4 Mon Sep 17 00:00:00 2001 From: Ruoyu Fu Date: Tue, 14 Jun 2016 16:14:59 -0700 Subject: [PATCH 019/260] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 75d51850..cd6fc8e6 100644 --- a/README.md +++ b/README.md @@ -89,11 +89,12 @@ platform :ios, '8.0' use_frameworks! target 'MyApp' do - pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git' + pod 'SwiftyJSON' end ``` Note that this requires CocoaPods version 36, and your iOS deployment target to be at least 8.0: + ####Carthage (iOS 8+, OS X 10.9+) You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: ``` From 2d4f4d0226257a0d78e3ffaf66186143db35b301 Mon Sep 17 00:00:00 2001 From: Ruoyu Fu Date: Tue, 14 Jun 2016 16:21:04 -0700 Subject: [PATCH 020/260] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cd6fc8e6..112cf609 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -#SwiftyJSON [中文介绍](http://tangplin.github.io/swiftyjson/) - +#SwiftyJSON + [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) SwiftyJSON makes it easy to deal with JSON data in Swift. @@ -17,6 +17,9 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. - [Setter](#setter) - [Raw object](#raw-object) - [Literal convertibles](#literal-convertibles) +> For Swift3 support, take a look at the [swift3 beta branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift3) +> [中文介绍](http://tangplin.github.io/swiftyjson/) + 1. [Work with Alamofire](#work-with-alamofire) ##Why is the typical JSON handling in Swift NOT good? From 4421d00c351215f14111f06f52fd97c740796ec0 Mon Sep 17 00:00:00 2001 From: Ruoyu Fu Date: Tue, 14 Jun 2016 16:21:32 -0700 Subject: [PATCH 021/260] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 112cf609..7a30af7f 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. - [Setter](#setter) - [Raw object](#raw-object) - [Literal convertibles](#literal-convertibles) + > For Swift3 support, take a look at the [swift3 beta branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift3) > [中文介绍](http://tangplin.github.io/swiftyjson/) From 29e8cf380dd9ff40970243b49312e2ad1cf33b02 Mon Sep 17 00:00:00 2001 From: Ruoyu Fu Date: Tue, 14 Jun 2016 16:22:21 -0700 Subject: [PATCH 022/260] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7a30af7f..e281dc5c 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. - [Literal convertibles](#literal-convertibles) > For Swift3 support, take a look at the [swift3 beta branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift3) + > [中文介绍](http://tangplin.github.io/swiftyjson/) 1. [Work with Alamofire](#work-with-alamofire) From 73670b94292b8d8496c398a973f56ac67789ba9f Mon Sep 17 00:00:00 2001 From: Ruoyu Fu Date: Tue, 14 Jun 2016 16:23:25 -0700 Subject: [PATCH 023/260] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e281dc5c..5c983cc5 100644 --- a/README.md +++ b/README.md @@ -17,12 +17,12 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. - [Setter](#setter) - [Raw object](#raw-object) - [Literal convertibles](#literal-convertibles) +1. [Work with Alamofire](#work-with-alamofire) > For Swift3 support, take a look at the [swift3 beta branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift3) > [中文介绍](http://tangplin.github.io/swiftyjson/) -1. [Work with Alamofire](#work-with-alamofire) ##Why is the typical JSON handling in Swift NOT good? Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. From cecab2b06d65f8e10e31858e3e17f972bb6d2e4e Mon Sep 17 00:00:00 2001 From: Jan Date: Fri, 17 Jun 2016 16:42:11 +0200 Subject: [PATCH 024/260] updated "Swift Package Manager" installation manual seems to be, that the Swift Package Manager has updated the kind of defining Versions. But on "swift build -v" we have still a issue: /Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin/swiftc --driver-mode=swift -I /Library/Developer/Toolchains/swift-latest.xctoolchain/usr/lib/swift/pm -L /Library/Developer/Toolchains/swift-latest.xctoolchain/usr/lib/swift/pm -lPackageDescription -target x86_64-apple-macosx10.10 /Users/jan/Development/iOS/Global\ Nights/Package.swift -fileno 4 /Users/jan/Development/iOS/Global Nights/Package.swift:15:17: error: incorrect argument labels in call (have 'url:tag:versions:', expected 'url:majorVersion:minor:') .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", tag: "2.3.3", versions: Version(1,0,0).. Date: Thu, 23 Jun 2016 12:01:51 +0400 Subject: [PATCH 025/260] Updated Year in License File --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index a7af1968..916a0acd 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014 Ruoyu Fu +Copyright (c) 2016 Ruoyu Fu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 700c8d2c9476588fc61db7d68924a24604cf7e32 Mon Sep 17 00:00:00 2001 From: Lucas Derraugh Date: Sat, 25 Jun 2016 05:39:01 -0400 Subject: [PATCH 026/260] Valid Swift 3.0 code Update Travis for Xcode 8 --- .travis.yml | 5 ++--- Source/SwiftyJSON.swift | 40 +++++++++++++++++------------------ Tests/RawTests.swift | 2 +- Tests/SequenceTypeTests.swift | 3 ++- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/.travis.yml b/.travis.yml index 24b06066..9d896ba4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: objective-c -osx_image: xcode7.1 -xcode_sdk: iphonesimulator9.0 +osx_image: xcode8 +xcode_sdk: iphonesimulator10.0 script: 'sh scripts/ci.sh' - diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index b639ac00..ad3d9564 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -195,16 +195,16 @@ public struct JSON { } public enum JSONIndex:Comparable { - case Array(Int) - case Dictionary(DictionaryIndex) - case Null + case array(Int) + case dictionary(DictionaryIndex) + case null } public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs, rhs) { - case (.Array(let left), .Array(let right)): + case (.array(let left), .array(let right)): return left == right - case (.Dictionary(let left), .Dictionary(let right)): + case (.dictionary(let left), .dictionary(let right)): return left == right default: return false @@ -213,9 +213,9 @@ public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs, rhs) { - case (.Array(let left), .Array(let right)): + case (.array(let left), .array(let right)): return left < right - case (.Dictionary(let left), .Dictionary(let right)): + case (.dictionary(let left), .dictionary(let right)): return left < right default: return false @@ -230,42 +230,42 @@ extension JSON: Collection{ public var startIndex: Index{ switch type { case .array: - return .Array(rawArray.startIndex) + return .array(rawArray.startIndex) case .dictionary: - return .Dictionary(dictionaryValue.startIndex) + return .dictionary(dictionaryValue.startIndex) default: - return .Null + return .null } } public var endIndex: Index{ switch type { case .array: - return .Array(rawArray.endIndex) + return .array(rawArray.endIndex) case .dictionary: - return .Dictionary(dictionaryValue.endIndex) + return .dictionary(dictionaryValue.endIndex) default: - return .Null + return .null } } public func index(after i: Index) -> Index { switch i { - case .Array(let idx): - return .Array(rawArray.index(after: idx)) - case .Dictionary(let idx): - return .Dictionary(dictionaryValue.index(after: idx)) + case .array(let idx): + return .array(rawArray.index(after: idx)) + case .dictionary(let idx): + return .dictionary(dictionaryValue.index(after: idx)) default: - return .Null + return .null } } public subscript (position: Index) -> (String, JSON) { switch position { - case .Array(let idx): + case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) - case .Dictionary(let idx): + case .dictionary(let idx): return dictionaryValue[idx] default: return ("", JSON.null) diff --git a/Tests/RawTests.swift b/Tests/RawTests.swift index 0799be36..7ba7a334 100644 --- a/Tests/RawTests.swift +++ b/Tests/RawTests.swift @@ -39,7 +39,7 @@ class RawTests: XCTestCase { func testInvalidJSONForRawData() { let json: JSON = "...xyz" do { - try json.rawData() + _ = try json.rawData() } catch let error as NSError { XCTAssertEqual(error.code, ErrorInvalidJSON) } diff --git a/Tests/SequenceTypeTests.swift b/Tests/SequenceTypeTests.swift index 467231f6..904b90b3 100644 --- a/Tests/SequenceTypeTests.swift +++ b/Tests/SequenceTypeTests.swift @@ -38,7 +38,8 @@ class SequenceTypeTests: XCTestCase { XCTAssertTrue(sub["id_str"] == "240556426106372096") case 2: XCTAssertTrue(sub["id_str"] == "240539141056638977") - default:0 + default: + continue } } } else { From 976ba4c487a0b29cb46f56109baf06fd29f9b51a Mon Sep 17 00:00:00 2001 From: Lucas Derraugh Date: Sat, 25 Jun 2016 06:31:43 -0400 Subject: [PATCH 027/260] Use Swift 3.0 for whole project --- SwiftyJSON.xcodeproj/project.pbxproj | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 10897c87..37c8464c 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -679,6 +679,7 @@ ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; @@ -721,6 +722,7 @@ METAL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -746,7 +748,6 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; - SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -768,7 +769,6 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; - SWIFT_VERSION = 3.0; }; name = Release; }; @@ -785,7 +785,6 @@ METAL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -798,7 +797,6 @@ METAL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 3.0; }; name = Release; }; From 580dc33a003b7800a604fb636019ebb347b687fd Mon Sep 17 00:00:00 2001 From: EyeOfTheStorm Date: Wed, 6 Jul 2016 14:29:13 +0200 Subject: [PATCH 028/260] filled Manifest Manifest file should not be empty in Swift 3.0 --- Package.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Package.swift b/Package.swift index e69de29b..801f1d5d 100644 --- a/Package.swift +++ b/Package.swift @@ -0,0 +1,4 @@ +import PackageDescription + +let package = Package( + name: "SwiftyJSON") From 536f3766b8ea2abdffe1ebb05b0a3f31af573f22 Mon Sep 17 00:00:00 2001 From: Mariam Date: Sat, 30 Jul 2016 12:19:12 +0300 Subject: [PATCH 029/260] Add Getting an array of string from a JSON Array --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 5c983cc5..dc0bd8c3 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,12 @@ if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allow //Getting a double from a JSON Array let name = json[0].double ``` + +```swift +//Getting an array of string from a JSON Array +let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue}) +``` + ```swift //Getting a string from a JSON Dictionary let name = json["name"].stringValue From 8e488dec25f3d1c83f74a51d880ab6fd376cb9a8 Mon Sep 17 00:00:00 2001 From: Evgeny Yurtaev Date: Wed, 17 Aug 2016 00:28:39 +0100 Subject: [PATCH 030/260] Small Readme fix "dictionary" is get-only property, should be dictionaryObject. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5c983cc5..dcd8834f 100644 --- a/README.md +++ b/README.md @@ -299,7 +299,7 @@ json["id"].int = 1234567890 json["coordinate"].double = 8766.766 json["name"].string = "Jack" json.arrayObject = [1,2,3,4] -json.dictionary = ["name":"Jack", "age":25] +json.dictionaryObject = ["name":"Jack", "age":25] ``` ####Raw object From fea362172a2a36c6491cd70021e508d8c2a5aaa9 Mon Sep 17 00:00:00 2001 From: Tom MacWright Date: Tue, 23 Aug 2016 17:13:21 -0400 Subject: [PATCH 031/260] Spelling fix: existence, not existance --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5c983cc5..9ca4c59c 100644 --- a/README.md +++ b/README.md @@ -321,7 +321,7 @@ if let string = json.rawString() { //Do something you want } ``` -####Existance +####Existence ```swift //shows you whether value specified in JSON or not if json["name"].isExists() From d2367f7df4608649c718b41dc8eab50db98327ee Mon Sep 17 00:00:00 2001 From: Jeff Kang Date: Thu, 1 Sep 2016 23:01:15 +0900 Subject: [PATCH 032/260] Basic playground set. --- Example/Playground.playground/Contents.swift | 11 + .../Resources/SwiftyJSONTests.json | 345 ++++++++++++++++++ 2 files changed, 356 insertions(+) create mode 100644 Example/Playground.playground/Resources/SwiftyJSONTests.json diff --git a/Example/Playground.playground/Contents.swift b/Example/Playground.playground/Contents.swift index 33ae9484..1ed77302 100644 --- a/Example/Playground.playground/Contents.swift +++ b/Example/Playground.playground/Contents.swift @@ -1,3 +1,14 @@ //: Playground - noun: a place where people can play import SwiftyJSON + +var testData: NSData? + +if let file = NSBundle.mainBundle().pathForResource("SwiftyJSONTests", ofType: "json") { + testData = NSData(contentsOfFile: file) +} else { + print("Fail") +} + +let json = JSON(data: testData!) +print(json[0]["text"]) \ No newline at end of file diff --git a/Example/Playground.playground/Resources/SwiftyJSONTests.json b/Example/Playground.playground/Resources/SwiftyJSONTests.json new file mode 100644 index 00000000..05190a8a --- /dev/null +++ b/Example/Playground.playground/Resources/SwiftyJSONTests.json @@ -0,0 +1,345 @@ +[ + { + "coordinates":null, + "truncated":false, + "created_at":"Tue Aug 28 21:16:23 +0000 2012", + "favorited":false, + "id_str":"240558470661799936", + "in_reply_to_user_id_str":null, + "entities":{ + "urls":[ + + ], + "hashtags":[ + + ], + "user_mentions":[ + + ] + }, + "text":"just another test", + "contributors":null, + "id":240558470661799936, + "retweet_count":0, + "in_reply_to_status_id_str":null, + "geo":null, + "retweeted":false, + "in_reply_to_user_id":null, + "place":null, + "source":"<a href=\"//realitytechnicians.com\" rel=\"\"nofollow\"\">OAuth Dancer Reborn</a>", + "user":{ + "name":"OAuth Dancer", + "profile_sidebar_fill_color":"DDEEF6", + "profile_background_tile":true, + "profile_sidebar_border_color":"C0DEED", + "profile_image_url":"http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg", + "created_at":"Wed Mar 03 19:37:35 +0000 2010", + "location":"San Francisco, CA", + "follow_request_sent":false, + "id_str":"119476949", + "is_translator":false, + "profile_link_color":"0084B4", + "entities":{ + "url":{ + "urls":[ + { + "expanded_url":null, + "url":"http://bit.ly/oauth-dancer", + "indices":[ + 0, + 26 + ], + "display_url":null + } + ] + }, + "description":null + }, + "default_profile":false, + "url":"http://bit.ly/oauth-dancer", + "contributors_enabled":false, + "favourites_count":7, + "utc_offset":null, + "profile_image_url_https":"https://si0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg", + "id":119476949, + "listed_count":1, + "profile_use_background_image":true, + "profile_text_color":"333333", + "followers_count":28, + "lang":"en", + "protected":false, + "geo_enabled":true, + "notifications":false, + "description":"", + "profile_background_color":"C0DEED", + "verified":false, + "time_zone":null, + "profile_background_image_url_https":"https://si0.twimg.com/profile_background_images/80151733/oauth-dance.png", + "statuses_count":166, + "profile_background_image_url":"http://a0.twimg.com/profile_background_images/80151733/oauth-dance.png", + "default_profile_image":false, + "friends_count":14, + "following":false, + "show_all_inline_media":false, + "screen_name":"oauth_dancer" + }, + "in_reply_to_screen_name":null, + "in_reply_to_status_id":null + }, + { + "coordinates":{ + "coordinates":[ + -122.25831, + 37.871609 + ], + "type":"Point" + }, + "truncated":false, + "created_at":"Tue Aug 28 21:08:15 +0000 2012", + "favorited":false, + "id_str":"240556426106372096", + "in_reply_to_user_id_str":null, + "entities":{ + "urls":[ + { + "expanded_url":"http://blogs.ischool.berkeley.edu/i290-abdt-s12/", + "url":"http://t.co/bfj7zkDJ", + "indices":[ + 79, + 99 + ], + "display_url":"blogs.ischool.berkeley.edu/i290-abdt-s12/" + } + ], + "hashtags":[ + + ], + "user_mentions":[ + { + "name":"Cal", + "id_str":"17445752", + "id":17445752, + "indices":[ + 60, + 64 + ], + "screen_name":"Cal" + }, + { + "name":"Othman Laraki", + "id_str":"20495814", + "id":20495814, + "indices":[ + 70, + 77 + ], + "screen_name":"othman" + } + ] + }, + "text":"lecturing at the \"analyzing big data with twitter\" class at @cal with @othman http://t.co/bfj7zkDJ", + "contributors":null, + "id":240556426106372096, + "retweet_count":3, + "in_reply_to_status_id_str":null, + "geo":{ + "coordinates":[ + 37.871609, + -122.25831 + ], + "type":"Point" + }, + "retweeted":false, + "possibly_sensitive":false, + "in_reply_to_user_id":null, + "place":{ + "name":"Berkeley", + "country_code":"US", + "country":"United States", + "attributes":{ + + }, + "url":"http://api.twitter.com/1/geo/id/5ef5b7f391e30aff.json", + "id":"5ef5b7f391e30aff", + "bounding_box":{ + "coordinates":[ + [ + [ + -122.367781, + 37.835727 + ], + [ + -122.234185, + 37.835727 + ], + [ + -122.234185, + 37.905824 + ], + [ + -122.367781, + 37.905824 + ] + ] + ], + "type":"Polygon" + }, + "full_name":"Berkeley, CA", + "place_type":"city" + }, + "source":"<a href=\"//www.apple.com\"\" rel=\"\"nofollow\"\">Safari on iOS</a>", + "user":{ + "name":"Raffi Krikorian", + "profile_sidebar_fill_color":"DDEEF6", + "profile_background_tile":false, + "profile_sidebar_border_color":"C0DEED", + "profile_image_url":"http://a0.twimg.com/profile_images/1270234259/raffi-headshot-casual_normal.png", + "created_at":"Sun Aug 19 14:24:06 +0000 2007", + "location":"San Francisco, California", + "follow_request_sent":false, + "id_str":"8285392", + "is_translator":false, + "profile_link_color":"0084B4", + "entities":{ + "url":{ + "urls":[ + { + "expanded_url":"http://about.me/raffi.krikorian", + "url":"http://t.co/eNmnM6q", + "indices":[ + 0, + 19 + ], + "display_url":"about.me/raffi.krikorian" + } + ] + }, + "description":{ + "urls":[ + + ] + } + }, + "default_profile":true, + "url":"http://t.co/eNmnM6q", + "contributors_enabled":false, + "favourites_count":724, + "utc_offset":-28800, + "profile_image_url_https":"https://si0.twimg.com/profile_images/1270234259/raffi-headshot-casual_normal.png", + "id":8285392, + "listed_count":619, + "profile_use_background_image":true, + "profile_text_color":"333333", + "followers_count":18752, + "lang":"en", + "protected":false, + "geo_enabled":true, + "notifications":false, + "description":"Director of @twittereng's Platform Services. I break things.", + "profile_background_color":"C0DEED", + "verified":false, + "time_zone":"Pacific Time (US & Canada)", + "profile_background_image_url_https":"https://si0.twimg.com/images/themes/theme1/bg.png", + "statuses_count":5007, + "profile_background_image_url":"http://a0.twimg.com/images/themes/theme1/bg.png", + "default_profile_image":false, + "friends_count":701, + "following":true, + "show_all_inline_media":true, + "screen_name":"raffi" + }, + "in_reply_to_screen_name":null, + "in_reply_to_status_id":null + }, + { + "coordinates":null, + "truncated":false, + "created_at":"Tue Aug 28 19:59:34 +0000 2012", + "favorited":false, + "id_str":"240539141056638977", + "in_reply_to_user_id_str":null, + "entities":{ + "urls":[ + + ], + "hashtags":[ + + ], + "user_mentions":[ + + ] + }, + "text":"You'd be right more often if you thought you were wrong.", + "contributors":null, + "id":240539141056638977, + "retweet_count":1, + "in_reply_to_status_id_str":null, + "geo":null, + "retweeted":false, + "in_reply_to_user_id":null, + "place":null, + "source":"web", + "user":{ + "name":"Taylor Singletary", + "profile_sidebar_fill_color":"FBFBFB", + "profile_background_tile":true, + "profile_sidebar_border_color":"000000", + "profile_image_url":"http://a0.twimg.com/profile_images/2546730059/f6a8zq58mg1hn0ha8vie_normal.jpeg", + "created_at":"Wed Mar 07 22:23:19 +0000 2007", + "location":"San Francisco, CA", + "follow_request_sent":false, + "id_str":"819797", + "is_translator":false, + "profile_link_color":"c71818", + "entities":{ + "url":{ + "urls":[ + { + "expanded_url":"http://www.rebelmouse.com/episod/", + "url":"http://t.co/Lxw7upbN", + "indices":[ + 0, + 20 + ], + "display_url":"rebelmouse.com/episod/" + } + ] + }, + "description":{ + "urls":[ + + ] + } + }, + "default_profile":false, + "url":"http://t.co/Lxw7upbN", + "contributors_enabled":false, + "favourites_count":15990, + "utc_offset":-28800, + "profile_image_url_https":"https://si0.twimg.com/profile_images/2546730059/f6a8zq58mg1hn0ha8vie_normal.jpeg", + "id":819797, + "listed_count":340, + "profile_use_background_image":true, + "profile_text_color":"D20909", + "followers_count":7126, + "lang":"en", + "protected":false, + "geo_enabled":true, + "notifications":false, + "description":"Reality Technician, Twitter API team, synthesizer enthusiast; a most excellent adventure in timelines. I know it's hard to believe in something you can't see.", + "profile_background_color":"000000", + "verified":false, + "time_zone":"Pacific Time (US & Canada)", + "profile_background_image_url_https":"https://si0.twimg.com/profile_background_images/643655842/hzfv12wini4q60zzrthg.png", + "statuses_count":18076, + "profile_background_image_url":"http://a0.twimg.com/profile_background_images/643655842/hzfv12wini4q60zzrthg.png", + "default_profile_image":false, + "friends_count":5444, + "following":true, + "show_all_inline_media":true, + "screen_name":"episod" + }, + "in_reply_to_screen_name":null, + "in_reply_to_status_id":null + } + ] \ No newline at end of file From cf657820fad3656df022d8ebf32f9cdd99e1247a Mon Sep 17 00:00:00 2001 From: Jason Neumeier Date: Sun, 18 Sep 2016 09:25:08 -0400 Subject: [PATCH 033/260] Updated main source and tests to spec for Swift 3.0 as released in Xcode 8/0 GM. --- Example/Example.xcodeproj/project.pbxproj | 15 +- Example/Example/AppDelegate.swift | 14 +- Example/Example/Base.lproj/LaunchScreen.xib | 12 +- Example/Example/Base.lproj/Main.storyboard | 29 +- .../AppIcon.appiconset/Contents.json | 25 + Example/Example/ViewController.swift | 36 +- Source/SwiftyJSON.swift | 430 +++++++++--------- Tests/BaseTests.swift | 8 +- Tests/DictionaryTests.swift | 2 +- Tests/LiteralConvertibleTests.swift | 2 +- Tests/NumberTests.swift | 7 +- Tests/PerformanceTests.swift | 16 +- Tests/PrintableTests.swift | 6 +- Tests/RawRepresentableTests.swift | 18 +- Tests/SequenceTypeTests.swift | 10 +- Tests/StringTests.swift | 4 +- 16 files changed, 342 insertions(+), 292 deletions(-) diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index cd37ea68..44393c89 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -186,11 +186,13 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0700; - LastUpgradeCheck = 0700; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = swiftyjson; TargetAttributes = { A82A1C1819D926B8009A653D = { CreatedOnToolsVersion = 6.0.1; + LastSwiftMigration = 0800; + ProvisioningStyle = Manual; }; }; }; @@ -329,8 +331,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; @@ -340,6 +344,7 @@ ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", @@ -374,8 +379,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "iPhone Distribution"; @@ -384,6 +391,7 @@ ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; @@ -393,6 +401,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -403,10 +412,12 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; + DEVELOPMENT_TEAM = ""; INFOPLIST_FILE = Example/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -416,10 +427,12 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; CODE_SIGN_IDENTITY = "iPhone Distribution"; + DEVELOPMENT_TEAM = ""; INFOPLIST_FILE = Example/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Release; }; diff --git a/Example/Example/AppDelegate.swift b/Example/Example/AppDelegate.swift index 77c528ff..31b98b35 100644 --- a/Example/Example/AppDelegate.swift +++ b/Example/Example/AppDelegate.swift @@ -28,15 +28,19 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let navigationController = self.window?.rootViewController as! UINavigationController let viewController = navigationController.topViewController as! ViewController - if let file = NSBundle(forClass:AppDelegate.self).pathForResource("SwiftyJSONTests", ofType: "json") { - let data = NSData(contentsOfFile: file)! - let json = JSON(data:data) - viewController.json = json + if let file = Bundle.main.path(forResource: "SwiftyJSONTests", ofType: "json") { + do { + let data = try Data(contentsOf: URL(fileURLWithPath: file)) + let json = JSON(data: data) + viewController.json = json + } catch { + viewController.json = JSON.null + } } else { viewController.json = JSON.null } diff --git a/Example/Example/Base.lproj/LaunchScreen.xib b/Example/Example/Base.lproj/LaunchScreen.xib index 0985c07c..b999ccb2 100644 --- a/Example/Example/Base.lproj/LaunchScreen.xib +++ b/Example/Example/Base.lproj/LaunchScreen.xib @@ -1,8 +1,10 @@ - - + + - + + + @@ -12,19 +14,17 @@ - + diff --git a/Example/Example/Base.lproj/Main.storyboard b/Example/Example/Base.lproj/Main.storyboard index 68803970..be1a65dc 100644 --- a/Example/Example/Base.lproj/Main.storyboard +++ b/Example/Example/Base.lproj/Main.storyboard @@ -1,13 +1,14 @@ - - + + - + + - + HelveticaNeue - + @@ -24,36 +25,36 @@ - + - + - + - + - + @@ -75,7 +76,7 @@ - + diff --git a/Example/Example/Images.xcassets/AppIcon.appiconset/Contents.json b/Example/Example/Images.xcassets/AppIcon.appiconset/Contents.json index 36d2c80d..1d060ed2 100644 --- a/Example/Example/Images.xcassets/AppIcon.appiconset/Contents.json +++ b/Example/Example/Images.xcassets/AppIcon.appiconset/Contents.json @@ -1,5 +1,15 @@ { "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, { "idiom" : "iphone", "size" : "29x29", @@ -30,6 +40,16 @@ "size" : "60x60", "scale" : "3x" }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, { "idiom" : "ipad", "size" : "29x29", @@ -59,6 +79,11 @@ "idiom" : "ipad", "size" : "76x76", "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" } ], "info" : { diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index a0e13463..373be9bb 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -29,30 +29,30 @@ class ViewController: UITableViewController { // MARK: - Table view data source - override func numberOfSectionsInTableView(tableView: UITableView) -> Int { + override func numberOfSections(in tableView: UITableView) -> Int { return 1 } - override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch self.json.type { - case Type.Array, Type.Dictionary: + case Type.array, Type.dictionary: return self.json.count default: return 1 } } - override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCellWithIdentifier("JSONCell", forIndexPath: indexPath) as UITableViewCell + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "JSONCell", for: indexPath) as UITableViewCell - let row = indexPath.row + let row = (indexPath as NSIndexPath).row switch self.json.type { - case .Array: + case .array: cell.textLabel?.text = "\(row)" cell.detailTextLabel?.text = self.json.arrayValue.description - case .Dictionary: - let key: AnyObject = Array(self.json.dictionaryValue.keys)[row] + case .dictionary: + let key: Any = Array(self.json.dictionaryValue.keys)[row] let value = self.json[key as! String] cell.textLabel?.text = "\(key)" cell.detailTextLabel?.text = value.description @@ -66,23 +66,23 @@ class ViewController: UITableViewController { // MARK: - Navigation - override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { + override func prepare(for segue: UIStoryboardSegue, sender: Any!) { var nextController: UIViewController? - switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) { - case .OrderedSame, .OrderedDescending: - nextController = (segue.destinationViewController as! UINavigationController).topViewController - case .OrderedAscending: - nextController = segue.destinationViewController + switch UIDevice.current.systemVersion.compare("8.0.0", options: NSString.CompareOptions.numeric) { + case .orderedSame, .orderedDescending: + nextController = (segue.destination as! UINavigationController).topViewController + case .orderedAscending: + nextController = segue.destination } if let indexPath = self.tableView.indexPathForSelectedRow { - let row = indexPath.row + let row = (indexPath as NSIndexPath).row var nextJson: JSON = JSON.null switch self.json.type { - case .Array: + case .array: nextJson = self.json[row] - case .Dictionary where row < self.json.dictionaryValue.count: + case .dictionary where row < self.json.dictionaryValue.count: let key = Array(self.json.dictionaryValue.keys)[row] if let value = self.json.dictionary?[key] { nextJson = value diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index ad3d9564..26180fec 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -37,12 +37,12 @@ public let ErrorInvalidJSON: Int = 490 // MARK: - JSON Type /** -JSON's type definitions. - -See http://www.json.org -*/ + JSON's type definitions. + + See http://www.json.org + */ public enum Type :Int{ - + case number case string case bool @@ -55,19 +55,19 @@ public enum Type :Int{ // MARK: - JSON Base public struct JSON { - + /** - Creates a JSON using the data. - - - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - - parameter error: error The NSErrorPointer used to return the error. `nil` by default. - - - returns: The created JSON - */ + Creates a JSON using the data. + + - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary + - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. + - parameter error: error The NSErrorPointer used to return the error. `nil` by default. + + - returns: The created JSON + */ public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer? = nil) { do { - let object: AnyObject = try JSONSerialization.jsonObject(with: data, options: opt) + let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(object) } catch let aError as NSError { if error != nil { @@ -76,68 +76,69 @@ public struct JSON { self.init(NSNull()) } } - + /** Create a JSON from JSON string - - parameter string: Normal json string like '{"a":"b"}' - - - returns: The created JSON - */ + - parameter string: Normal json string like '{"a":"b"}' + + - returns: The created JSON + */ public static func parse(_ string:String) -> JSON { return string.data(using: String.Encoding.utf8) .flatMap({JSON(data: $0)}) ?? JSON(NSNull()) } - + /** - Creates a JSON using the object. - - - 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. - - - returns: The created JSON - */ - public init(_ object: AnyObject) { + Creates a JSON using the object. + + - 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. + + - returns: The created JSON + */ + public init(_ object: Any) { self.object = object } - + /** - Creates a JSON from a [JSON] - - - parameter jsonArray: A Swift array of JSON objects - - - returns: The created JSON - */ + Creates a JSON from a [JSON] + + - parameter jsonArray: A Swift array of JSON objects + + - returns: The created JSON + */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } - + /** - Creates a JSON from a [String: JSON] - - - parameter jsonDictionary: A Swift dictionary of JSON objects - - - returns: The created JSON - */ + Creates a JSON from a [String: JSON] + + - parameter jsonDictionary: A Swift dictionary of JSON objects + + - returns: The created JSON + */ public init(_ jsonDictionary:[String: JSON]) { - var dictionary = [String: AnyObject](minimumCapacity: jsonDictionary.count) + var dictionary = [String: Any](minimumCapacity: jsonDictionary.count) for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary) } - + /// Private object - private var rawArray: [AnyObject] = [] - private var rawDictionary: [String : AnyObject] = [:] - private var rawString: String = "" - private var rawNumber: NSNumber = 0 - private var rawNull: NSNull = NSNull() + fileprivate var rawArray: [Any] = [] + fileprivate var rawDictionary: [String : Any] = [:] + fileprivate var rawString: String = "" + fileprivate var rawNumber: NSNumber = 0 + fileprivate var rawNull: NSNull = NSNull() + fileprivate var rawBool: Bool = false /// Private type - private var _type: Type = .null + fileprivate var _type: Type = .null /// prviate error - private var _error: NSError? = nil - + fileprivate var _error: NSError? = nil + /// Object in JSON - public var object: AnyObject { + public var object: Any { get { switch self.type { case .array: @@ -149,7 +150,7 @@ public struct JSON { case .number: return self.rawNumber case .bool: - return self.rawNumber + return self.rawBool default: return self.rawNull } @@ -160,19 +161,20 @@ public struct JSON { case let number as NSNumber: if number.isBool { _type = .bool + self.rawBool = number.boolValue } else { _type = .number + self.rawNumber = number } - self.rawNumber = number case let string as String: _type = .string self.rawString = string case _ as NSNull: _type = .null - case let array as [AnyObject]: + case let array as [Any]: _type = .array self.rawArray = array - case let dictionary as [String : AnyObject]: + case let dictionary as [String : Any]: _type = .dictionary self.rawDictionary = dictionary default: @@ -181,13 +183,13 @@ public struct JSON { } } } - + /// json type public var type: Type { get { return _type } } - + /// Error in JSON public var error: NSError? { get { return self._error } } - + /// The static null json @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } @@ -224,9 +226,9 @@ public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { extension JSON: Collection{ - + public typealias Index = JSONIndex - + public var startIndex: Index{ switch type { case .array: @@ -237,7 +239,7 @@ extension JSON: Collection{ return .null } } - + public var endIndex: Index{ switch type { case .array: @@ -248,7 +250,7 @@ extension JSON: Collection{ return .null } } - + public func index(after i: Index) -> Index { switch i { case .array(let idx): @@ -258,9 +260,9 @@ extension JSON: Collection{ default: return .null } - + } - + public subscript (position: Index) -> (String, JSON) { switch position { case .array(let idx): @@ -271,15 +273,15 @@ extension JSON: Collection{ return ("", JSON.null) } } - - + + } // MARK: - Subscript /** -* To mark both String and Int can be used in subscript. -*/ + * To mark both String and Int can be used in subscript. + */ public enum JSONKey { case index(Int) case key(String) @@ -302,9 +304,9 @@ extension String: JSONSubscriptType { } extension JSON { - + /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. - private subscript(index index: Int) -> JSON { + fileprivate subscript(index index: Int) -> JSON { get { if self.type != .array { var r = JSON.null @@ -326,9 +328,9 @@ extension JSON { } } } - + /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. - private subscript(key key: String) -> JSON { + fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .dictionary { @@ -348,9 +350,9 @@ extension JSON { } } } - + /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. - private subscript(sub sub: JSONSubscriptType) -> JSON { + fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] @@ -364,20 +366,20 @@ extension JSON { } } } - + /** - Find a json in the complex data structuresby using the Int/String's array. - - - parameter path: The target json's path. Example: - - let json = JSON[data] - let path = [9,"list","person","name"] - let name = json[path] - - The same as: let name = json[9]["list"]["person"]["name"] - - - returns: Return a json found by the path or a null json with error - */ + Find a json in the complex data structuresby using the Int/String's array. + + - parameter path: The target json's path. Example: + + let json = JSON[data] + let path = [9,"list","person","name"] + let name = json[path] + + The same as: let name = json[9]["list"]["person"]["name"] + + - returns: Return a json found by the path or a null json with error + */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } @@ -396,18 +398,18 @@ extension JSON { } } } - + /** - Find a json in the complex data structures by using the Int/String's array. - - - parameter path: The target json's path. Example: - - let name = json[9,"list","person","name"] - - The same as: let name = json[9]["list"]["person"]["name"] - - - returns: Return a json found by the path or a null json with error - */ + Find a json in the complex data structures by using the Int/String's array. + + - parameter path: The target json's path. Example: + + let name = json[9,"list","person","name"] + + The same as: let name = json[9]["list"]["person"]["name"] + + - returns: Return a json found by the path or a null json with error + */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] @@ -420,91 +422,91 @@ extension JSON { // MARK: - LiteralConvertible -extension JSON: Swift.StringLiteralConvertible { - +extension JSON: Swift.ExpressibleByStringLiteral { + public init(stringLiteral value: StringLiteralType) { - self.init(value) + self.init(value as Any) } - + public init(extendedGraphemeClusterLiteral value: StringLiteralType) { - self.init(value) + self.init(value as Any) } - + public init(unicodeScalarLiteral value: StringLiteralType) { - self.init(value) + self.init(value as Any) } } -extension JSON: Swift.IntegerLiteralConvertible { - +extension JSON: Swift.ExpressibleByIntegerLiteral { + public init(integerLiteral value: IntegerLiteralType) { - self.init(value) + self.init(value as Any) } } -extension JSON: Swift.BooleanLiteralConvertible { - +extension JSON: Swift.ExpressibleByBooleanLiteral { + public init(booleanLiteral value: BooleanLiteralType) { - self.init(value) + self.init(value as Any) } } -extension JSON: Swift.FloatLiteralConvertible { - +extension JSON: Swift.ExpressibleByFloatLiteral { + public init(floatLiteral value: FloatLiteralType) { - self.init(value) + self.init(value as Any) } } -extension JSON: Swift.DictionaryLiteralConvertible { - - public init(dictionaryLiteral elements: (String, AnyObject)...) { - self.init(elements.reduce([String : AnyObject](minimumCapacity: elements.count)){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in +extension JSON: Swift.ExpressibleByDictionaryLiteral { + + public init(dictionaryLiteral elements: (String, Any)...) { + self.init(elements.reduce([String : Any](minimumCapacity: elements.count)){(dictionary: [String : Any], element:(String, Any)) -> [String : Any] in var d = dictionary d[element.0] = element.1 return d - }) + } as Any) } } -extension JSON: Swift.ArrayLiteralConvertible { - - public init(arrayLiteral elements: AnyObject...) { - self.init(elements) +extension JSON: Swift.ExpressibleByArrayLiteral { + + public init(arrayLiteral elements: Any...) { + self.init(elements as Any) } } -extension JSON: Swift.NilLiteralConvertible { - +extension JSON: Swift.ExpressibleByNilLiteral { + public init(nilLiteral: ()) { - self.init(NSNull()) + self.init(NSNull() as Any) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { - - public init?(rawValue: AnyObject) { + + public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } - - public var rawValue: AnyObject { + + public var rawValue: Any { return self.object } - + public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } - + return try JSONSerialization.data(withJSONObject: self.object, options: opt) } - + public func rawString(_ encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { switch self.type { case .array, .dictionary: @@ -519,7 +521,7 @@ extension JSON: Swift.RawRepresentable { case .number: return self.rawNumber.stringValue case .bool: - return self.rawNumber.boolValue.description + return self.rawBool.description case .null: return "null" default: @@ -531,7 +533,7 @@ extension JSON: Swift.RawRepresentable { // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { - + public var description: String { if let string = self.rawString(options:.prettyPrinted) { return string @@ -539,7 +541,7 @@ extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertibl return "unknown" } } - + public var debugDescription: String { return description } @@ -548,7 +550,7 @@ extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertibl // MARK: - Array extension JSON { - + //Optional [JSON] public var array: [JSON]? { get { @@ -559,16 +561,16 @@ extension JSON { } } } - + //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } - + //Optional [AnyObject] - public var arrayObject: [AnyObject]? { + public var arrayObject: [Any]? { get { switch self.type { case .array: @@ -579,7 +581,7 @@ extension JSON { } set { if let array = newValue { - self.object = array + self.object = array as Any } else { self.object = NSNull() } @@ -590,12 +592,12 @@ extension JSON { // MARK: - Dictionary extension JSON { - + //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { - - return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in + + return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, Any)) -> [String : JSON] in var d = dictionary d[element.0] = JSON(element.1) return d @@ -604,14 +606,14 @@ extension JSON { return nil } } - + //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } - + //Optional [String : AnyObject] - public var dictionaryObject: [String : AnyObject]? { + public var dictionaryObject: [String : Any]? { get { switch self.type { case .dictionary: @@ -622,7 +624,7 @@ extension JSON { } set { if let v = newValue { - self.object = v + self.object = v as Any } else { self.object = NSNull() } @@ -632,39 +634,43 @@ extension JSON { // MARK: - Bool -extension JSON: Swift.Boolean { - +extension JSON { // : Swift.Bool + //Optional bool public var bool: Bool? { get { switch self.type { case .bool: - return self.rawNumber.boolValue + return self.rawBool default: return nil } } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + self.object = newValue as Bool } else { self.object = NSNull() } } } - + //Non-optional bool public var boolValue: Bool { get { switch self.type { - case .bool, .number, .string: - return self.object.boolValue + case .bool: + return self.rawBool + case .number: + return self.rawNumber.boolValue + case .string: + return self.rawString.caseInsensitiveCompare("true") == .orderedSame default: return false } } set { - self.object = NSNumber(value: newValue) + self.object = newValue } } } @@ -672,7 +678,7 @@ extension JSON: Swift.Boolean { // MARK: - String extension JSON { - + //Optional string public var string: String? { get { @@ -691,7 +697,7 @@ extension JSON { } } } - + //Non-optional string public var stringValue: String { get { @@ -699,7 +705,7 @@ extension JSON { case .string: return self.object as? String ?? "" case .number: - return self.object.stringValue + return self.rawNumber.stringValue case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: @@ -714,13 +720,15 @@ extension JSON { // MARK: - Number extension JSON { - + //Optional number public var number: NSNumber? { get { switch self.type { - case .number, .bool: + case .number: return self.rawNumber + case .bool: + return NSNumber(value: self.rawBool ? 1 : 0) default: return nil } @@ -729,19 +737,21 @@ extension JSON { self.object = newValue ?? NSNull() } } - + //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .string: let decimal = NSDecimalNumber(string: self.object as? String) - if decimal == NSDecimalNumber.notANumber() { // indicates parse error - return NSDecimalNumber.zero() + if decimal == NSDecimalNumber.notANumber { // indicates parse error + return NSDecimalNumber.zero } return decimal - case .number, .bool: + case .number: return self.object as? NSNumber ?? NSNumber(value: 0) + case .bool: + return NSNumber(value: self.rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } @@ -754,7 +764,7 @@ extension JSON { //MARK: - Null extension JSON { - + public var null: NSNull? { get { switch self.type { @@ -769,7 +779,7 @@ extension JSON { } } public func exists() -> Bool{ - if let errorValue = error where errorValue.code == ErrorNotExist{ + if let errorValue = error , errorValue.code == ErrorNotExist{ return false } return true @@ -778,14 +788,14 @@ extension JSON { //MARK: - URL extension JSON { - + //Optional URL - public var URL: Foundation.URL? { + public var URL: NSURL? { get { switch self.type { case .string: if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { - return Foundation.URL(string: encodedString_) + return NSURL(string: encodedString_) } else { return nil } @@ -794,7 +804,7 @@ extension JSON { } } set { - self.object = newValue?.absoluteString ?? NSNull() + self.object = newValue?.absoluteString } } } @@ -802,7 +812,7 @@ extension JSON { // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { - + public var double: Double? { get { return self.number?.doubleValue @@ -815,7 +825,7 @@ extension JSON { } } } - + public var doubleValue: Double { get { return self.numberValue.doubleValue @@ -824,7 +834,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var float: Float? { get { return self.number?.floatValue @@ -837,7 +847,7 @@ extension JSON { } } } - + public var floatValue: Float { get { return self.numberValue.floatValue @@ -846,7 +856,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int: Int? { get { return self.number?.intValue @@ -859,7 +869,7 @@ extension JSON { } } } - + public var intValue: Int { get { return self.numberValue.intValue @@ -868,7 +878,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt: UInt? { get { return self.number?.uintValue @@ -881,7 +891,7 @@ extension JSON { } } } - + public var uIntValue: UInt { get { return self.numberValue.uintValue @@ -890,7 +900,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int8: Int8? { get { return self.number?.int8Value @@ -903,7 +913,7 @@ extension JSON { } } } - + public var int8Value: Int8 { get { return self.numberValue.int8Value @@ -912,7 +922,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt8: UInt8? { get { return self.number?.uint8Value @@ -925,7 +935,7 @@ extension JSON { } } } - + public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value @@ -934,7 +944,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int16: Int16? { get { return self.number?.int16Value @@ -947,7 +957,7 @@ extension JSON { } } } - + public var int16Value: Int16 { get { return self.numberValue.int16Value @@ -956,7 +966,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt16: UInt16? { get { return self.number?.uint16Value @@ -969,7 +979,7 @@ extension JSON { } } } - + public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value @@ -978,7 +988,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int32: Int32? { get { return self.number?.int32Value @@ -991,7 +1001,7 @@ extension JSON { } } } - + public var int32Value: Int32 { get { return self.numberValue.int32Value @@ -1000,7 +1010,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt32: UInt32? { get { return self.number?.uint32Value @@ -1013,7 +1023,7 @@ extension JSON { } } } - + public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value @@ -1022,7 +1032,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int64: Int64? { get { return self.number?.int64Value @@ -1035,7 +1045,7 @@ extension JSON { } } } - + public var int64Value: Int64 { get { return self.numberValue.int64Value @@ -1044,7 +1054,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt64: UInt64? { get { return self.number?.uint64Value @@ -1057,7 +1067,7 @@ extension JSON { } } } - + public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value @@ -1072,14 +1082,14 @@ extension JSON { extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): - return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue + return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): @@ -1092,14 +1102,14 @@ public func ==(lhs: JSON, rhs: JSON) -> Bool { } public func <=(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): - return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue + return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): @@ -1112,14 +1122,14 @@ public func <=(lhs: JSON, rhs: JSON) -> Bool { } public func >=(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): - return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue + return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): @@ -1132,7 +1142,7 @@ public func >=(lhs: JSON, rhs: JSON) -> Bool { } public func >(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber @@ -1144,7 +1154,7 @@ public func >(lhs: JSON, rhs: JSON) -> Bool { } public func <(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber @@ -1168,7 +1178,7 @@ extension NSNumber { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == ComparisonResult.orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == ComparisonResult.orderedSame && objCType == falseObjCType){ - return true + return true } else { return false } @@ -1192,7 +1202,7 @@ func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { - + switch (lhs.isBool, rhs.isBool) { case (false, true): return false @@ -1204,7 +1214,7 @@ func <(lhs: NSNumber, rhs: NSNumber) -> Bool { } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { - + switch (lhs.isBool, rhs.isBool) { case (false, true): return false @@ -1216,7 +1226,7 @@ func >(lhs: NSNumber, rhs: NSNumber) -> Bool { } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { - + switch (lhs.isBool, rhs.isBool) { case (false, true): return false @@ -1228,7 +1238,7 @@ func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { - + switch (lhs.isBool, rhs.isBool) { case (false, true): return false diff --git a/Tests/BaseTests.swift b/Tests/BaseTests.swift index fd462c5e..12b03233 100644 --- a/Tests/BaseTests.swift +++ b/Tests/BaseTests.swift @@ -31,7 +31,7 @@ class BaseTests: XCTestCase { super.setUp() - if let file = Bundle(for:BaseTests.self).pathForResource("Tests", ofType: "json") { + if let file = Bundle(for:BaseTests.self).path(forResource: "Tests", ofType: "json") { self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { XCTFail("Can't find the test JSON file") @@ -52,7 +52,7 @@ class BaseTests: XCTestCase { dictionary.setObject(NSNull(), forKey: "null" as NSString) _ = JSON(dictionary) do { - let object: AnyObject = try JSONSerialization.jsonObject(with: self.testData, options: []) + let object: Any = try JSONSerialization.jsonObject(with: self.testData, options: []) let json2 = JSON(object) XCTAssertEqual(json0, json2) } catch _ { @@ -122,13 +122,13 @@ class BaseTests: XCTestCase { let user_name = user["name"].string let user_profile_image_url = user["profile_image_url"].URL XCTAssert(user_name == "OAuth Dancer") - XCTAssert(user_profile_image_url == URL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) + XCTAssert(user_profile_image_url == NSURL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) let user_dictionary = json[0]["user"].dictionary let user_dictionary_name = user_dictionary?["name"]?.string let user_dictionary_name_profile_image_url = user_dictionary?["profile_image_url"]?.URL XCTAssert(user_dictionary_name == "OAuth Dancer") - XCTAssert(user_dictionary_name_profile_image_url == URL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) + XCTAssert(user_dictionary_name_profile_image_url == NSURL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) } func testJSONNumberCompare() { diff --git a/Tests/DictionaryTests.swift b/Tests/DictionaryTests.swift index 84d110d3..12074ed3 100644 --- a/Tests/DictionaryTests.swift +++ b/Tests/DictionaryTests.swift @@ -26,7 +26,7 @@ import SwiftyJSON class DictionaryTests: XCTestCase { func testGetter() { - let dictionary = ["number":9823.212, "name":"NAME", "list":[1234, 4.212], "object":["sub_number":877.2323, "sub_name":"sub_name"], "bool":true] + let dictionary = ["number":9823.212, "name":"NAME", "list":[1234, 4.212], "object":["sub_number":877.2323, "sub_name":"sub_name"], "bool":true] as [String : Any] let json = JSON(dictionary) //dictionary XCTAssertEqual((json.dictionary!["number"]! as JSON).double!, 9823.212) diff --git a/Tests/LiteralConvertibleTests.swift b/Tests/LiteralConvertibleTests.swift index ecbfb3fc..1f6cf031 100644 --- a/Tests/LiteralConvertibleTests.swift +++ b/Tests/LiteralConvertibleTests.swift @@ -53,7 +53,7 @@ class LiteralConvertibleTests: XCTestCase { func testNil() { let jsonNil_1:JSON = nil XCTAssert(jsonNil_1 == nil) - let jsonNil_2:JSON = JSON(NSNull) + let jsonNil_2:JSON = JSON(NSNull.self) XCTAssert(jsonNil_2 != nil) let jsonNil_3:JSON = JSON([1:2]) XCTAssert(jsonNil_3 != nil) diff --git a/Tests/NumberTests.swift b/Tests/NumberTests.swift index 8e19517b..e578bf83 100644 --- a/Tests/NumberTests.swift +++ b/Tests/NumberTests.swift @@ -22,6 +22,7 @@ import XCTest import SwiftyJSON + class NumberTests: XCTestCase { func testNumber() { @@ -327,7 +328,7 @@ class NumberTests: XCTestCase { } func testUInt32() { - let n2147483648 = NSNumber(value: 2147483648) + let n2147483648 = NSNumber(value: 2147483648 as UInt32) var json = JSON(n2147483648) XCTAssertTrue(json.uInt32! == n2147483648.uint32Value) XCTAssertTrue(json.uInt32Value == n2147483648.uint32Value) @@ -335,7 +336,7 @@ class NumberTests: XCTestCase { XCTAssertEqual(json.numberValue, n2147483648) XCTAssertEqual(json.stringValue, "2147483648") - let n32767 = NSNumber(value: 32767) + let n32767 = NSNumber(value: 32767 as UInt32) json.uInt32 = n32767.uint32Value XCTAssertTrue(json.uInt32! == n32767.uint32Value) XCTAssertTrue(json.uInt32Value == n32767.uint32Value) @@ -343,7 +344,7 @@ class NumberTests: XCTestCase { XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") - let n0 = NSNumber(value: 0) + let n0 = NSNumber(value: 0 as UInt32) json.uInt32Value = n0.uint32Value XCTAssertTrue(json.uInt32! == n0.uint32Value) XCTAssertTrue(json.uInt32Value == n0.uint32Value) diff --git a/Tests/PerformanceTests.swift b/Tests/PerformanceTests.swift index 18a10ea1..21b9b31f 100644 --- a/Tests/PerformanceTests.swift +++ b/Tests/PerformanceTests.swift @@ -30,7 +30,7 @@ class PerformanceTests: XCTestCase { override func setUp() { super.setUp() - if let file = Bundle(for:PerformanceTests.self).pathForResource("Tests", ofType: "json") { + if let file = Bundle(for:PerformanceTests.self).path(forResource: "Tests", ofType: "json") { self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { XCTFail("Can't find the test JSON file") @@ -52,10 +52,10 @@ class PerformanceTests: XCTestCase { } func testObjectMethodPerformance() { - var json = JSON(data:self.testData) + let json = JSON(data:self.testData) self.measure() { for _ in 1...100 { - let object:AnyObject? = json.object + let object:Any? = json.object XCTAssertTrue(object != nil) } } @@ -66,8 +66,9 @@ class PerformanceTests: XCTestCase { self.measure() { for _ in 1...100 { autoreleasepool{ - let array = json.array - XCTAssertTrue(array?.count > 0) + if let array = json.array { + XCTAssertTrue(array.count > 0) + } } } } @@ -78,8 +79,9 @@ class PerformanceTests: XCTestCase { self.measure() { for _ in 1...100 { autoreleasepool{ - let dictionary = json.dictionary - XCTAssertTrue(dictionary?.count > 0) + if let dictionary = json.dictionary { + XCTAssertTrue(dictionary.count > 0) + } } } } diff --git a/Tests/PrintableTests.swift b/Tests/PrintableTests.swift index 72448288..e9d38811 100644 --- a/Tests/PrintableTests.swift +++ b/Tests/PrintableTests.swift @@ -68,8 +68,8 @@ class PrintableTests: XCTestCase { var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) - XCTAssertTrue(debugDescription.range(of: "\"1\":2", options: NSString.CompareOptions.caseInsensitiveSearch) != nil) - XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: NSString.CompareOptions.caseInsensitiveSearch) != nil) - XCTAssertTrue(debugDescription.range(of: "\"3\":3", options: NSString.CompareOptions.caseInsensitiveSearch) != nil) + XCTAssertTrue(debugDescription.range(of: "\"1\":2", options: String.CompareOptions.caseInsensitive) != nil) + XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: String.CompareOptions.caseInsensitive) != nil) + XCTAssertTrue(debugDescription.range(of: "\"3\":3", options: String.CompareOptions.caseInsensitive) != nil) } } diff --git a/Tests/RawRepresentableTests.swift b/Tests/RawRepresentableTests.swift index e9412481..c4e79258 100644 --- a/Tests/RawRepresentableTests.swift +++ b/Tests/RawRepresentableTests.swift @@ -34,7 +34,7 @@ class RawRepresentableTests: XCTestCase { XCTAssertTrue(json.float! == 948394394.347384) XCTAssertTrue(json.floatValue == 948394394.347384) - let object: AnyObject = json.rawValue + let object: Any = json.rawValue XCTAssertEqual(object as? Int, 948394394) XCTAssertEqual(object as? Double, 948394394.347384) XCTAssertTrue(object as! Float == 948394394.347384) @@ -50,17 +50,11 @@ class RawRepresentableTests: XCTestCase { XCTAssertEqual(jsonFalse.bool!, false) XCTAssertEqual(jsonFalse.boolValue, false) - let objectTrue: AnyObject = jsonTrue.rawValue - XCTAssertEqual(objectTrue as? Int, 1) - XCTAssertEqual(objectTrue as? Double, 1.0) + let objectTrue = jsonTrue.rawValue XCTAssertEqual(objectTrue as? Bool, true) - XCTAssertEqual(objectTrue as? NSNumber, NSNumber(value: true)) - let objectFalse: AnyObject = jsonFalse.rawValue - XCTAssertEqual(objectFalse as? Int, 0) - XCTAssertEqual(objectFalse as? Double, 0.0) + let objectFalse = jsonFalse.rawValue XCTAssertEqual(objectFalse as? Bool, false) - XCTAssertEqual(objectFalse as? NSNumber, NSNumber(value: false)) } func testString() { @@ -78,7 +72,7 @@ class RawRepresentableTests: XCTestCase { XCTFail("Should not run into here") } - let object: AnyObject = JSON(rawValue: string)!.rawValue + let object: Any = JSON(rawValue: string)!.rawValue XCTAssertEqual(object as? String, string) } @@ -94,7 +88,7 @@ class RawRepresentableTests: XCTestCase { XCTAssertEqual(json, JSON(array)) } - let object: AnyObject = JSON(rawValue: array)!.rawValue + let object: Any = JSON(rawValue: array)!.rawValue XCTAssertTrue(array == object as! NSArray) } @@ -104,7 +98,7 @@ class RawRepresentableTests: XCTestCase { XCTAssertEqual(json, JSON(dictionary)) } - let object: AnyObject = JSON(rawValue: dictionary)!.rawValue + let object: Any = JSON(rawValue: dictionary)!.rawValue XCTAssertTrue(dictionary == object as! NSDictionary) } } diff --git a/Tests/SequenceTypeTests.swift b/Tests/SequenceTypeTests.swift index 904b90b3..3aae1c19 100644 --- a/Tests/SequenceTypeTests.swift +++ b/Tests/SequenceTypeTests.swift @@ -27,7 +27,7 @@ import SwiftyJSON class SequenceTypeTests: XCTestCase { func testJSONFile() { - if let file = Bundle(for:BaseTests.self).pathForResource("Tests", ofType: "json") { + if let file = Bundle(for:BaseTests.self).path(forResource: "Tests", ofType: "json") { let testData = try? Data(contentsOf: URL(fileURLWithPath: file)) let json = JSON(data:testData!) for (index, sub) in json { @@ -104,7 +104,7 @@ class SequenceTypeTests: XCTestCase { for (i, sub) in json { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") - array.append(sub.object) + array.append(sub.object as AnyObject) index += 1 } XCTAssertEqual(index, 4) @@ -121,7 +121,7 @@ class SequenceTypeTests: XCTestCase { for (i, sub) in json { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") - array.append(sub.object) + array.append(sub.object as AnyObject) index += 1 } XCTAssertEqual(index, 3) @@ -191,7 +191,7 @@ class SequenceTypeTests: XCTestCase { var dictionary = [String:AnyObject]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) - dictionary[key] = sub.object + dictionary[key] = sub.object as AnyObject? index += 1 } @@ -210,7 +210,7 @@ class SequenceTypeTests: XCTestCase { var dictionary = [String:AnyObject]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) - dictionary[key] = sub.object + dictionary[key] = sub.object as AnyObject? index += 1 } diff --git a/Tests/StringTests.swift b/Tests/StringTests.swift index 8e720be4..e79992cc 100644 --- a/Tests/StringTests.swift +++ b/Tests/StringTests.swift @@ -38,7 +38,7 @@ class StringTests: XCTestCase { func testURL() { let json = JSON("http://github.com") - XCTAssertEqual(json.URL!, URL(string:"http://github.com")!) + XCTAssertEqual(json.URL!, NSURL(string:"http://github.com")!) } func testURLPercentEscapes() { @@ -46,6 +46,6 @@ class StringTests: XCTestCase { let urlString = "http://examble.com/unencoded" + emDash + "string" let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) let json = JSON(urlString) - XCTAssertEqual(json.URL!, URL(string: encodedURLString!)!, "Wrong unpacked ") + XCTAssertEqual(json.URL!, NSURL(string: encodedURLString!)!, "Wrong unpacked ") } } From e20cbab49fc0f67c6a8dcfbf4c370b905506bce5 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Wed, 21 Sep 2016 22:09:33 +0800 Subject: [PATCH 034/260] Update readme file for swift3 --- README.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 5c983cc5..492f1e29 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,25 @@ #SwiftyJSON - + [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) SwiftyJSON makes it easy to deal with JSON data in Swift. 1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) -1. [Requirements](#requirements) -1. [Integration](#integration) -1. [Usage](#usage) - - [Initialization](#initialization) - - [Subscript](#subscript) - - [Loop](#loop) - - [Error](#error) - - [Optional getter](#optional-getter) - - [Non-optional getter](#non-optional-getter) - - [Setter](#setter) - - [Raw object](#raw-object) - - [Literal convertibles](#literal-convertibles) -1. [Work with Alamofire](#work-with-alamofire) - -> For Swift3 support, take a look at the [swift3 beta branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift3) +2. [Requirements](#requirements) +3. [Integration](#integration) +4. [Usage](#usage) + - [Initialization](#initialization) + - [Subscript](#subscript) + - [Loop](#loop) + - [Error](#error) + - [Optional getter](#optional-getter) + - [Non-optional getter](#non-optional-getter) + - [Setter](#setter) + - [Raw object](#raw-object) + - [Literal convertibles](#literal-convertibles) +5. [Work with Alamofire](#work-with-alamofire) + +> For Legacy Swift support, take a look at the [swift2 branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift2) > [中文介绍](http://tangplin.github.io/swiftyjson/) @@ -83,7 +83,7 @@ if let userName = json[999999]["wrong_key"]["wrong_name"].string { ## Requirements - iOS 7.0+ / OS X 10.9+ -- Xcode 7 +- Xcode 8 ##Integration From f6d8c921034c58e19bc34b6aa5d0d3f9c345e3f1 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Wed, 21 Sep 2016 22:16:21 +0800 Subject: [PATCH 035/260] Update pod version --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 1a9d29dd..335ca965 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "2.3.2" + s.version = "3.0.0" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } From c8a6bda9aa0e823b4c0ec1e74f19869d77c4bed4 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Wed, 21 Sep 2016 22:19:34 +0800 Subject: [PATCH 036/260] Add .swift-version --- .swift-version | 1 + 1 file changed, 1 insertion(+) create mode 100644 .swift-version diff --git a/.swift-version b/.swift-version new file mode 100644 index 00000000..9f55b2cc --- /dev/null +++ b/.swift-version @@ -0,0 +1 @@ +3.0 From 87dae80939b9163cc2b2a5d90215a6e8e133bebe Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Wed, 21 Sep 2016 22:41:26 +0800 Subject: [PATCH 037/260] Set APPLICATION_EXTENSION_API_ONLY to yes for macOS target from https://github.com/SwiftyJSON/SwiftyJSON/pull/616 --- SwiftyJSON.xcodeproj/project.pbxproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 37c8464c..d8c3a749 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -847,6 +847,7 @@ 9C7DFC6F1A9102BD005AA3F7 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_IDENTITY = ""; COMBINE_HIDPI_IMAGES = YES; DEFINES_MODULE = YES; @@ -873,6 +874,7 @@ 9C7DFC701A9102BD005AA3F7 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_IDENTITY = ""; COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; From 497e8eb9f350c7af41f425274a1a3afef724d79a Mon Sep 17 00:00:00 2001 From: Lukas Zielinski Date: Wed, 21 Sep 2016 17:29:41 +0200 Subject: [PATCH 038/260] Update NSErrorPointer usage in initializer. --- Source/SwiftyJSON.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 26180fec..12e796d9 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -65,13 +65,13 @@ public struct JSON { - returns: The created JSON */ - public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer? = nil) { + public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { do { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(object) } catch let aError as NSError { if error != nil { - error??.pointee = aError + error?.pointee = aError } self.init(NSNull()) } From 1090ce6299d32479be7a5321926991277a923bb2 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Wed, 21 Sep 2016 23:58:52 +0800 Subject: [PATCH 039/260] Update code signing change to fix .travisCI --- SwiftyJSON.xcodeproj/project.pbxproj | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index d8c3a749..6f5c58f4 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -431,6 +431,7 @@ 2E4FEFE519575BE100351305 = { CreatedOnToolsVersion = 6.0; LastSwiftMigration = 0800; + ProvisioningStyle = Manual; TestTargetID = 2E4FEFDA19575BE100351305; }; 9C7DFC5A1A9102BD005AA3F7 = { @@ -735,8 +736,6 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -756,8 +755,6 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -775,6 +772,8 @@ 2E4FEFF519575BE100351305 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CODE_SIGN_IDENTITY = ""; + DEVELOPMENT_TEAM = ""; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", @@ -791,6 +790,8 @@ 2E4FEFF619575BE100351305 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CODE_SIGN_IDENTITY = ""; + DEVELOPMENT_TEAM = ""; INFOPLIST_FILE = "Tests/Info-iOS.plist"; IPHONEOS_DEPLOYMENT_TARGET = 9.1; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -933,6 +934,7 @@ A8580F7D1BCF5C5B00DA927B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CODE_SIGN_IDENTITY = ""; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = "Tests/Info-tvOS.plist"; @@ -948,6 +950,7 @@ A8580F7E1BCF5C5B00DA927B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CODE_SIGN_IDENTITY = ""; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; From e7729f35da2fad24f2ea9e036207aaf39e2ef2e3 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Thu, 22 Sep 2016 00:05:24 +0800 Subject: [PATCH 040/260] Fix example app in xcode 8 --- Example/Example.xcodeproj/project.pbxproj | 132 +--------------------- 1 file changed, 6 insertions(+), 126 deletions(-) diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index 44393c89..717e1606 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + 04733F521D92E6ED002E3A99 /* SwiftyJSON.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 04733F511D92E6ED002E3A99 /* SwiftyJSON.framework */; }; + 04733F531D92E6ED002E3A99 /* SwiftyJSON.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 04733F511D92E6ED002E3A99 /* SwiftyJSON.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; A82A1C1F19D926B8009A653D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A82A1C1E19D926B8009A653D /* AppDelegate.swift */; }; A82A1C2419D926B8009A653D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A82A1C2219D926B8009A653D /* Main.storyboard */; }; A82A1C2619D926B8009A653D /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A82A1C2519D926B8009A653D /* Images.xcassets */; }; @@ -15,58 +17,6 @@ A82A1C5619D95606009A653D /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A82A1C5519D95606009A653D /* ViewController.swift */; }; /* End PBXBuildFile section */ -/* Begin PBXContainerItemProxy section */ - 04294C581BE5A9DE00D0397E /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = E4D7CCE81B9465A700EE7221; - remoteInfo = "SwiftyJSON watchOS"; - }; - 04294C5A1BE5A9DE00D0397E /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 7236B4F61BAC14150020529B; - remoteInfo = "SwiftyJSON tvOS"; - }; - 04294C5C1BE5A9DE00D0397E /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = A8580F741BCF5C5B00DA927B; - remoteInfo = "SwiftyJSON tvOS Tests"; - }; - A8BF45AA1B871E100066C032 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 2E4FEFDB19575BE100351305; - remoteInfo = "SwiftyJSON iOS"; - }; - A8BF45AC1B871E100066C032 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 2E4FEFE619575BE100351305; - remoteInfo = "SwiftyJSON iOS Tests"; - }; - A8BF45AE1B871E100066C032 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 9C7DFC5B1A9102BD005AA3F7; - remoteInfo = "SwiftyJSON OSX"; - }; - A8BF45B01B871E100066C032 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 9C7DFC651A9102BD005AA3F7; - remoteInfo = "SwiftyJSON OSX Tests"; - }; -/* End PBXContainerItemProxy section */ - /* Begin PBXCopyFilesBuildPhase section */ A82A1C5419D94E97009A653D /* Embed Frameworks */ = { isa = PBXCopyFilesBuildPhase; @@ -74,6 +24,7 @@ dstPath = ""; dstSubfolderSpec = 10; files = ( + 04733F531D92E6ED002E3A99 /* SwiftyJSON.framework in Embed Frameworks */, ); name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; @@ -82,6 +33,7 @@ /* Begin PBXFileReference section */ 04294C501BE5A9DE00D0397E /* Playground.playground */ = {isa = PBXFileReference; lastKnownFileType = file.playground; path = Playground.playground; sourceTree = ""; }; + 04733F511D92E6ED002E3A99 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A82A1C1919D926B8009A653D /* Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Example.app; sourceTree = BUILT_PRODUCTS_DIR; }; A82A1C1D19D926B8009A653D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; A82A1C1E19D926B8009A653D /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -89,7 +41,6 @@ A82A1C2519D926B8009A653D /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; A82A1C2819D926B8009A653D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = ""; }; A82A1C3F19D94AE5009A653D /* SwiftyJSONTests.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = SwiftyJSONTests.json; sourceTree = ""; }; - A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = SwiftyJSON.xcodeproj; path = ../SwiftyJSON.xcodeproj; sourceTree = ""; }; A82A1C5519D95606009A653D /* ViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -98,6 +49,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 04733F521D92E6ED002E3A99 /* SwiftyJSON.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -107,8 +59,8 @@ A82A1C1019D926B8009A653D = { isa = PBXGroup; children = ( + 04733F511D92E6ED002E3A99 /* SwiftyJSON.framework */, 04294C501BE5A9DE00D0397E /* Playground.playground */, - A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */, A82A1C1B19D926B8009A653D /* Example */, A82A1C1A19D926B8009A653D /* Products */, ); @@ -144,20 +96,6 @@ name = "Supporting Files"; sourceTree = ""; }; - A8BF45A41B871E0F0066C032 /* Products */ = { - isa = PBXGroup; - children = ( - A8BF45AB1B871E100066C032 /* SwiftyJSON.framework */, - A8BF45AD1B871E100066C032 /* SwiftyJSON iOS Tests.xctest */, - A8BF45AF1B871E100066C032 /* SwiftyJSON.framework */, - A8BF45B11B871E100066C032 /* SwiftyJSON OSX Tests.xctest */, - 04294C591BE5A9DE00D0397E /* SwiftyJSON.framework */, - 04294C5B1BE5A9DE00D0397E /* SwiftyJSON.framework */, - 04294C5D1BE5A9DE00D0397E /* SwiftyJSON tvOS Tests.xctest */, - ); - name = Products; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -207,12 +145,6 @@ mainGroup = A82A1C1019D926B8009A653D; productRefGroup = A82A1C1A19D926B8009A653D /* Products */; projectDirPath = ""; - projectReferences = ( - { - ProductGroup = A8BF45A41B871E0F0066C032 /* Products */; - ProjectRef = A82A1C4719D94E86009A653D /* SwiftyJSON.xcodeproj */; - }, - ); projectRoot = ""; targets = ( A82A1C1819D926B8009A653D /* Example */, @@ -220,58 +152,6 @@ }; /* End PBXProject section */ -/* Begin PBXReferenceProxy section */ - 04294C591BE5A9DE00D0397E /* SwiftyJSON.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = SwiftyJSON.framework; - remoteRef = 04294C581BE5A9DE00D0397E /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 04294C5B1BE5A9DE00D0397E /* SwiftyJSON.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = SwiftyJSON.framework; - remoteRef = 04294C5A1BE5A9DE00D0397E /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 04294C5D1BE5A9DE00D0397E /* SwiftyJSON tvOS Tests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = "SwiftyJSON tvOS Tests.xctest"; - remoteRef = 04294C5C1BE5A9DE00D0397E /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - A8BF45AB1B871E100066C032 /* SwiftyJSON.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = SwiftyJSON.framework; - remoteRef = A8BF45AA1B871E100066C032 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - A8BF45AD1B871E100066C032 /* SwiftyJSON iOS Tests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = "SwiftyJSON iOS Tests.xctest"; - remoteRef = A8BF45AC1B871E100066C032 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - A8BF45AF1B871E100066C032 /* SwiftyJSON.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = SwiftyJSON.framework; - remoteRef = A8BF45AE1B871E100066C032 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - A8BF45B11B871E100066C032 /* SwiftyJSON OSX Tests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = "SwiftyJSON OSX Tests.xctest"; - remoteRef = A8BF45B01B871E100066C032 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; -/* End PBXReferenceProxy section */ - /* Begin PBXResourcesBuildPhase section */ A82A1C1719D926B8009A653D /* Resources */ = { isa = PBXResourcesBuildPhase; From 78fb8311bab86bacbeb8a9d9f5afe75c15eaea54 Mon Sep 17 00:00:00 2001 From: James C Date: Thu, 12 May 2016 08:36:17 -0400 Subject: [PATCH 041/260] Add checks on exists method for errors - Check for out of bounds error on exists method - Check for wrong type error on exists method - Add tests for cases where out of bounds and wrong type errors occur --- Source/SwiftyJSON.swift | 6 ++++-- Tests/BaseTests.swift | 7 +++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 12e796d9..2c7f718d 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -779,8 +779,10 @@ extension JSON { } } public func exists() -> Bool{ - if let errorValue = error , errorValue.code == ErrorNotExist{ - return false + if let errorValue = error, errorValue.code == ErrorNotExist || + errorValue.code == ErrorIndexOutOfBounds || + errorValue.code == ErrorWrongType { + return false } return true } diff --git a/Tests/BaseTests.swift b/Tests/BaseTests.swift index 12b03233..2ce24a4b 100644 --- a/Tests/BaseTests.swift +++ b/Tests/BaseTests.swift @@ -214,7 +214,14 @@ class BaseTests: XCTestCase { let dictionary = ["number":1111] let json = JSON(dictionary) XCTAssertFalse(json["unspecifiedValue"].exists()) + XCTAssertFalse(json[0].exists()) XCTAssertTrue(json["number"].exists()) + + let array = [["number":1111]] + let jsonForArray = JSON(array) + XCTAssertTrue(jsonForArray[0].exists()) + XCTAssertFalse(jsonForArray[1].exists()) + XCTAssertFalse(jsonForArray["someValue"].exists()) } func testErrorHandle() { From 46e888a19fae39e2a23b780dec808e3e15bf76d0 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Thu, 22 Sep 2016 13:15:47 +0800 Subject: [PATCH 042/260] Fix travis CI --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9d896ba4..14a93dd0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,4 +3,6 @@ language: objective-c osx_image: xcode8 xcode_sdk: iphonesimulator10.0 -script: 'sh scripts/ci.sh' +script: + - rvm get head # https://github.com/travis-ci/travis-ci/issues/6307 + - 'sh scripts/ci.sh' From 5e29a8b86c5763d95fa0b207319d5c735d37df01 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Thu, 22 Sep 2016 13:31:20 +0800 Subject: [PATCH 043/260] Add cocoapods and platform badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4e53998e..0b75b2da 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ #SwiftyJSON -[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg)![Platform](https://img.shields.io/badge/platforms-iOS%20%7C%20OSX%20%7C%20tvOS%20%7C%20watchOS-333333.svg) SwiftyJSON makes it easy to deal with JSON data in Swift. From 995fe225e75febcb605412126a7203a7b38d2575 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Thu, 22 Sep 2016 13:37:23 +0800 Subject: [PATCH 044/260] Update min target for macOS to 10.10 Also update platform iOS and README --- README.md | 4 ++-- SwiftyJSON.xcodeproj/project.pbxproj | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0b75b2da..085c4ee9 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ #SwiftyJSON -[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg)![Platform](https://img.shields.io/badge/platforms-iOS%20%7C%20OSX%20%7C%20tvOS%20%7C%20watchOS-333333.svg) +[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg)![Platform](https://img.shields.io/badge/platforms-iOS%208.0+%20%7C%20macOS%2010.10+%20%7C%20tvOS%209.0+%20%7C%20watchOS%202.0+-333333.svg) SwiftyJSON makes it easy to deal with JSON data in Swift. @@ -82,7 +82,7 @@ if let userName = json[999999]["wrong_key"]["wrong_name"].string { ## Requirements -- iOS 7.0+ / OS X 10.9+ +- iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+ - Xcode 8 ##Integration diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 6f5c58f4..4156ddf1 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -863,6 +863,7 @@ INFOPLIST_FILE = "Source/Info-OSX.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = YES; PLIST_FILE_OUTPUT_FORMAT = binary; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; @@ -887,6 +888,7 @@ INFOPLIST_FILE = "Source/Info-OSX.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = NO; PLIST_FILE_OUTPUT_FORMAT = binary; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; From 5c526116cf3945f3bc3679bd9ef94df71006b231 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Thu, 22 Sep 2016 13:41:24 +0800 Subject: [PATCH 045/260] Add spaces to badge icons --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 085c4ee9..891c0ead 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ #SwiftyJSON -[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg)![Platform](https://img.shields.io/badge/platforms-iOS%208.0+%20%7C%20macOS%2010.10+%20%7C%20tvOS%209.0+%20%7C%20watchOS%202.0+-333333.svg) +[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0+%20%7C%20macOS%2010.10+%20%7C%20tvOS%209.0+%20%7C%20watchOS%202.0+-333333.svg) SwiftyJSON makes it easy to deal with JSON data in Swift. From 0df304865c059bdf0b786eb01cfb1d1f8f16c729 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Thu, 22 Sep 2016 13:44:49 +0800 Subject: [PATCH 046/260] Fix test in macOS target --- SwiftyJSON.xcodeproj/project.pbxproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 4156ddf1..32ea7003 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -910,6 +910,7 @@ ); INFOPLIST_FILE = "Tests/Info-OSX.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -926,6 +927,7 @@ FRAMEWORK_SEARCH_PATHS = ""; INFOPLIST_FILE = "Tests/Info-OSX.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; From e953aa7d8796c0b114e07516f00698b8158247e0 Mon Sep 17 00:00:00 2001 From: Vijaya Prakash Kandel Date: Fri, 23 Sep 2016 07:43:08 +0200 Subject: [PATCH 047/260] Typos in Comments correction Added little more descriptive comment. --- Source/SwiftyJSON.swift | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 12e796d9..bd33db6b 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -61,7 +61,7 @@ public struct JSON { - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - - parameter error: error The NSErrorPointer used to return the error. `nil` by default. + - parameter error: The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ @@ -78,14 +78,14 @@ public struct JSON { } /** - Create a JSON from JSON string + Creates a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ public static func parse(_ string:String) -> JSON { return string.data(using: String.Encoding.utf8) - .flatMap({JSON(data: $0)}) ?? JSON(NSNull()) + .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) } /** @@ -184,13 +184,13 @@ public struct JSON { } } - /// json type + /// JSON type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } - /// The static null json + /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } @@ -368,7 +368,7 @@ extension JSON { } /** - Find a json in the complex data structuresby using the Int/String's array. + Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: @@ -400,7 +400,7 @@ extension JSON { } /** - Find a json in the complex data structures by using the Int/String's array. + Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: From 21507827a7d81daccd08529b87230c6768b4e3c7 Mon Sep 17 00:00:00 2001 From: Aaron Pearce Date: Mon, 26 Sep 2016 13:17:55 +1300 Subject: [PATCH 048/260] Move from NSURL to URL --- Source/SwiftyJSON.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index bd33db6b..0b1eb3c4 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -790,12 +790,13 @@ extension JSON { extension JSON { //Optional URL - public var URL: NSURL? { + public var URL: URL? { get { switch self.type { case .string: if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { - return NSURL(string: encodedString_) + // We have to use `Foundation.URL` otherwise it conflicts with the variable name. + return Foundation.URL(string: encodedString_) } else { return nil } From f6264e721048298ce66959f298a27aa09165efd3 Mon Sep 17 00:00:00 2001 From: Aaron Pearce Date: Mon, 26 Sep 2016 15:36:59 +1300 Subject: [PATCH 049/260] Fix the URL tests --- Tests/StringTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/StringTests.swift b/Tests/StringTests.swift index e79992cc..8e720be4 100644 --- a/Tests/StringTests.swift +++ b/Tests/StringTests.swift @@ -38,7 +38,7 @@ class StringTests: XCTestCase { func testURL() { let json = JSON("http://github.com") - XCTAssertEqual(json.URL!, NSURL(string:"http://github.com")!) + XCTAssertEqual(json.URL!, URL(string:"http://github.com")!) } func testURLPercentEscapes() { @@ -46,6 +46,6 @@ class StringTests: XCTestCase { let urlString = "http://examble.com/unencoded" + emDash + "string" let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) let json = JSON(urlString) - XCTAssertEqual(json.URL!, NSURL(string: encodedURLString!)!, "Wrong unpacked ") + XCTAssertEqual(json.URL!, URL(string: encodedURLString!)!, "Wrong unpacked ") } } From c23d428a796ab554ccb936a4b3b426498fe5ee84 Mon Sep 17 00:00:00 2001 From: Aaron Pearce Date: Mon, 26 Sep 2016 15:38:25 +1300 Subject: [PATCH 050/260] Update BaseTests with new URL --- Tests/BaseTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/BaseTests.swift b/Tests/BaseTests.swift index 12b03233..ed7163a4 100644 --- a/Tests/BaseTests.swift +++ b/Tests/BaseTests.swift @@ -122,13 +122,13 @@ class BaseTests: XCTestCase { let user_name = user["name"].string let user_profile_image_url = user["profile_image_url"].URL XCTAssert(user_name == "OAuth Dancer") - XCTAssert(user_profile_image_url == NSURL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) + XCTAssert(user_profile_image_url == URL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) let user_dictionary = json[0]["user"].dictionary let user_dictionary_name = user_dictionary?["name"]?.string let user_dictionary_name_profile_image_url = user_dictionary?["profile_image_url"]?.URL XCTAssert(user_dictionary_name == "OAuth Dancer") - XCTAssert(user_dictionary_name_profile_image_url == NSURL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) + XCTAssert(user_dictionary_name_profile_image_url == URL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) } func testJSONNumberCompare() { From 197889498df0e5e79a8a474ad4124412efc03f36 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Mon, 26 Sep 2016 12:40:26 +0800 Subject: [PATCH 051/260] Fix infinite loop with JSON.null --- Source/SwiftyJSON.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 12e796d9..9ecec2db 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -208,6 +208,7 @@ public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { return left == right case (.dictionary(let left), .dictionary(let right)): return left == right + case (.null, .null): return true default: return false } From d075ce98e9c0cfe608a6ff1b28389527dc3cf718 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Mon, 26 Sep 2016 14:23:55 +0800 Subject: [PATCH 052/260] Update pod version for 3.1.0 --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 335ca965..57c55b70 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "3.0.0" + s.version = "3.1.0" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } From aba949498551d27829ab8b27ad9b21de08e5aef2 Mon Sep 17 00:00:00 2001 From: Sami Suteria Date: Mon, 26 Sep 2016 21:58:53 -0700 Subject: [PATCH 053/260] update readme with nested example --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 891c0ead..2c7f5709 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,15 @@ json["list",3,"what"] = "that" let path = ["list",3,"what"] json[path] = "that" ``` +```swift +//With other JSON objects +let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] +let auth: JSON = [ + "user": user.object //use user.object instead of just user + "apikey": "supersecretapitoken" +] +```` + ##Work with Alamofire SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: From 1c84dbe72cea0e979dd8608a5835638ebe7f6f13 Mon Sep 17 00:00:00 2001 From: Hector Matos Date: Tue, 27 Sep 2016 15:17:17 -0700 Subject: [PATCH 054/260] adds support for nested JSON in literals --- Source/SwiftyJSON.swift | 207 +++++++++++++++------------ SwiftyJSON.xcodeproj/project.pbxproj | 8 ++ Tests/NestedJSONTests.swift | 42 ++++++ 3 files changed, 168 insertions(+), 89 deletions(-) create mode 100644 Tests/NestedJSONTests.swift diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index dd7c5ae8..bb4ddb52 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -34,6 +34,12 @@ public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 +///Types +private let trueNumber = NSNumber(value: true) +private let falseNumber = NSNumber(value: false) +private let trueObjCType = String(cString: trueNumber.objCType) +private let falseObjCType = String(cString: falseNumber.objCType) + // MARK: - JSON Type /** @@ -52,8 +58,85 @@ public enum Type :Int{ case unknown } -// MARK: - JSON Base +// MARK: - NSNumber: Comparable +extension NSNumber { + var isBool:Bool { + get { + let objCType = String(cString: self.objCType) + if (self.compare(trueNumber) == ComparisonResult.orderedSame && objCType == trueObjCType) + || (self.compare(falseNumber) == ComparisonResult.orderedSame && objCType == falseObjCType){ + return true + } else { + return false + } + } + } +} + +func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == ComparisonResult.orderedSame + } +} + +func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { + return !(lhs == rhs) +} +func <(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == ComparisonResult.orderedAscending + } +} + +func >(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == ComparisonResult.orderedDescending + } +} + +func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) != ComparisonResult.orderedDescending + } +} + +func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) != ComparisonResult.orderedAscending + } +} + +// MARK: - JSON Base public struct JSON { /** @@ -171,6 +254,9 @@ public struct JSON { self.rawString = string case _ as NSNull: _type = .null + case let array as [JSON]: + _type = .array + self.rawArray = array.map { $0.object } case let array as [Any]: _type = .array self.rawArray = array @@ -460,11 +546,38 @@ extension JSON: Swift.ExpressibleByFloatLiteral { } extension JSON: Swift.ExpressibleByDictionaryLiteral { - public init(dictionaryLiteral elements: (String, Any)...) { + let array = elements + self.init(dictionaryLiteral: array) + } + + public init(dictionaryLiteral elements: [(String, Any)]) { + let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in + let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in + if let value = dictionary[key] { + return (key, value) + } + return nil + } + return JSON(dictionaryLiteral: initializeElement) + } + self.init(elements.reduce([String : Any](minimumCapacity: elements.count)){(dictionary: [String : Any], element:(String, Any)) -> [String : Any] in var d = dictionary - d[element.0] = element.1 + let elementToSet: Any + if let json = element.1 as? JSON { + elementToSet = json.object + } else if let jsonArray = element.1 as? [JSON] { + elementToSet = JSON(jsonArray).object + } else if let dictionary = element.1 as? [String : Any] { + elementToSet = jsonFromDictionaryLiteral(dictionary).object + } else if let dictArray = element.1 as? [[String : Any]] { + let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) } + elementToSet = JSON(jsonArray).object + } else { + elementToSet = element.1 + } + d[element.0] = elementToSet return d } as Any) } @@ -783,7 +896,7 @@ extension JSON { if let errorValue = error, errorValue.code == ErrorNotExist || errorValue.code == ErrorIndexOutOfBounds || errorValue.code == ErrorWrongType { - return false + return false } return true } @@ -935,7 +1048,7 @@ extension JSON { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { - self.object = NSNull() + self.object = NSNull() } } } @@ -1168,87 +1281,3 @@ public func <(lhs: JSON, rhs: JSON) -> Bool { return false } } - -private let trueNumber = NSNumber(value: true) -private let falseNumber = NSNumber(value: false) -private let trueObjCType = String(cString: trueNumber.objCType) -private let falseObjCType = String(cString: falseNumber.objCType) - -// MARK: - NSNumber: Comparable - -extension NSNumber { - var isBool:Bool { - get { - let objCType = String(cString: self.objCType) - if (self.compare(trueNumber) == ComparisonResult.orderedSame && objCType == trueObjCType) - || (self.compare(falseNumber) == ComparisonResult.orderedSame && objCType == falseObjCType){ - return true - } else { - return false - } - } - } -} - -func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == ComparisonResult.orderedSame - } -} - -func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { - return !(lhs == rhs) -} - -func <(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == ComparisonResult.orderedAscending - } -} - -func >(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == ComparisonResult.orderedDescending - } -} - -func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) != ComparisonResult.orderedDescending - } -} - -func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) != ComparisonResult.orderedAscending - } -} diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 32ea7003..0b4bd070 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -9,6 +9,9 @@ /* Begin PBXBuildFile section */ 2E4FEFE119575BE100351305 /* SwiftyJSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E4FEFE019575BE100351305 /* SwiftyJSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2E4FEFE719575BE100351305 /* SwiftyJSON.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2E4FEFDB19575BE100351305 /* SwiftyJSON.framework */; }; + 5DD502911D9B21810004C112 /* NestedJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD502901D9B21810004C112 /* NestedJSONTests.swift */; }; + 5DD502921D9B21810004C112 /* NestedJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD502901D9B21810004C112 /* NestedJSONTests.swift */; }; + 5DD502931D9B21810004C112 /* NestedJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD502901D9B21810004C112 /* NestedJSONTests.swift */; }; 7236B4EE1BAC14150020529B /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8491E1D19CD6DAE00CCFAE6 /* SwiftyJSON.swift */; }; 7236B4F11BAC14150020529B /* SwiftyJSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E4FEFE019575BE100351305 /* SwiftyJSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; 9C459EF41A910334008C9A41 /* SwiftyJSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E4FEFE019575BE100351305 /* SwiftyJSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -92,6 +95,7 @@ 2E4FEFDF19575BE100351305 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; 2E4FEFE019575BE100351305 /* SwiftyJSON.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SwiftyJSON.h; sourceTree = ""; }; 2E4FEFE619575BE100351305 /* SwiftyJSON iOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON iOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 5DD502901D9B21810004C112 /* NestedJSONTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NestedJSONTests.swift; sourceTree = ""; }; 7236B4F61BAC14150020529B /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 7236B4F71BAC14150020529B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-tvOS.plist"; sourceTree = ""; }; 9C459EF61A9103B1008C9A41 /* Info-OSX.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Info-OSX.plist"; sourceTree = ""; }; @@ -225,6 +229,7 @@ A885D1DA19CFCFF0002FD4C3 /* Tests.json */, A86BAA0D19EBC32B009EAAEB /* PerformanceTests.swift */, A885D1D119CF1EE6002FD4C3 /* BaseTests.swift */, + 5DD502901D9B21810004C112 /* NestedJSONTests.swift */, A87080E319E3C2A600CDE086 /* SequenceTypeTests.swift */, A819C4A019E37FC600ADCC3D /* PrintableTests.swift */, A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */, @@ -538,6 +543,7 @@ files = ( A87080E819E439DA00CDE086 /* NumberTests.swift in Sources */, A87080E419E3C2A600CDE086 /* SequenceTypeTests.swift in Sources */, + 5DD502911D9B21810004C112 /* NestedJSONTests.swift in Sources */, A86BAA0E19EBC32B009EAAEB /* PerformanceTests.swift in Sources */, A819C49919E1B10300ADCC3D /* RawRepresentableTests.swift in Sources */, A819C49F19E2EE5B00ADCC3D /* SubscriptTests.swift in Sources */, @@ -574,6 +580,7 @@ files = ( 9C459EFB1A9103C1008C9A41 /* SequenceTypeTests.swift in Sources */, 9C459F001A9103C1008C9A41 /* ComparableTests.swift in Sources */, + 5DD502921D9B21810004C112 /* NestedJSONTests.swift in Sources */, 9C459F021A9103C1008C9A41 /* NumberTests.swift in Sources */, 9C459EFF1A9103C1008C9A41 /* RawRepresentableTests.swift in Sources */, 9C459EFA1A9103C1008C9A41 /* BaseTests.swift in Sources */, @@ -594,6 +601,7 @@ files = ( A8580F801BCF69A000DA927B /* PerformanceTests.swift in Sources */, A8580F811BCF69A000DA927B /* BaseTests.swift in Sources */, + 5DD502931D9B21810004C112 /* NestedJSONTests.swift in Sources */, A8580F821BCF69A000DA927B /* SequenceTypeTests.swift in Sources */, A8580F831BCF69A000DA927B /* PrintableTests.swift in Sources */, A8580F841BCF69A000DA927B /* SubscriptTests.swift in Sources */, diff --git a/Tests/NestedJSONTests.swift b/Tests/NestedJSONTests.swift new file mode 100644 index 00000000..5c75def7 --- /dev/null +++ b/Tests/NestedJSONTests.swift @@ -0,0 +1,42 @@ +// +// NestedJSONTests.swift +// SwiftyJSON +// +// Created by Hector Matos on 9/27/16. +// +// + +import XCTest +import SwiftyJSON + +class NestedJSONTests: XCTestCase { + let family: JSON = [ + "names" : [ + "Brooke Abigail Matos", + "Rowan Danger Matos" + ], + "motto" : "Hey, I don't know about you, but I'm feeling twenty-two! So, release the KrakenDev!" + ] + + func testTopLevelNestedJSON() { + let nestedJSON: JSON = [ + "family" : family + ] + XCTAssertNotNil(try? nestedJSON.rawData()) + } + + func testDeeplyNestedJSON() { + let nestedFamily: JSON = [ + "count": 1, + "families": [ + [ + "isACoolFamily" : true, + "family" : [ + "hello" : family + ] + ] + ] + ] + XCTAssertNotNil(try? nestedFamily.rawData()) + } +} From 46eb9a35f86e3d2f050e85526ad97e5fd3d4c030 Mon Sep 17 00:00:00 2001 From: Hector Matos Date: Tue, 27 Sep 2016 15:20:52 -0700 Subject: [PATCH 055/260] reverts improper moving of code --- Source/SwiftyJSON.swift | 174 ++++++++++++++++++++-------------------- 1 file changed, 87 insertions(+), 87 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index bb4ddb52..5a69a106 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -34,12 +34,6 @@ public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 -///Types -private let trueNumber = NSNumber(value: true) -private let falseNumber = NSNumber(value: false) -private let trueObjCType = String(cString: trueNumber.objCType) -private let falseObjCType = String(cString: falseNumber.objCType) - // MARK: - JSON Type /** @@ -58,84 +52,6 @@ public enum Type :Int{ case unknown } -// MARK: - NSNumber: Comparable -extension NSNumber { - var isBool:Bool { - get { - let objCType = String(cString: self.objCType) - if (self.compare(trueNumber) == ComparisonResult.orderedSame && objCType == trueObjCType) - || (self.compare(falseNumber) == ComparisonResult.orderedSame && objCType == falseObjCType){ - return true - } else { - return false - } - } - } -} - -func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == ComparisonResult.orderedSame - } -} - -func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { - return !(lhs == rhs) -} - -func <(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == ComparisonResult.orderedAscending - } -} - -func >(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == ComparisonResult.orderedDescending - } -} - -func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) != ComparisonResult.orderedDescending - } -} - -func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) != ComparisonResult.orderedAscending - } -} - // MARK: - JSON Base public struct JSON { @@ -579,7 +495,7 @@ extension JSON: Swift.ExpressibleByDictionaryLiteral { } d[element.0] = elementToSet return d - } as Any) + } as Any) } } @@ -896,7 +812,7 @@ extension JSON { if let errorValue = error, errorValue.code == ErrorNotExist || errorValue.code == ErrorIndexOutOfBounds || errorValue.code == ErrorWrongType { - return false + return false } return true } @@ -1048,7 +964,7 @@ extension JSON { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { - self.object = NSNull() + self.object = NSNull() } } } @@ -1281,3 +1197,87 @@ public func <(lhs: JSON, rhs: JSON) -> Bool { return false } } + +private let trueNumber = NSNumber(value: true) +private let falseNumber = NSNumber(value: false) +private let trueObjCType = String(cString: trueNumber.objCType) +private let falseObjCType = String(cString: falseNumber.objCType) + +// MARK: - NSNumber: Comparable + +extension NSNumber { + var isBool:Bool { + get { + let objCType = String(cString: self.objCType) + if (self.compare(trueNumber) == ComparisonResult.orderedSame && objCType == trueObjCType) + || (self.compare(falseNumber) == ComparisonResult.orderedSame && objCType == falseObjCType){ + return true + } else { + return false + } + } + } +} + +func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == ComparisonResult.orderedSame + } +} + +func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { + return !(lhs == rhs) +} + +func <(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == ComparisonResult.orderedAscending + } +} + +func >(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == ComparisonResult.orderedDescending + } +} + +func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) != ComparisonResult.orderedDescending + } +} + +func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) != ComparisonResult.orderedAscending + } +} From b0cff7c266ae7e521d05176df9ed277f0c6fd872 Mon Sep 17 00:00:00 2001 From: Hector Matos Date: Tue, 27 Sep 2016 15:56:11 -0700 Subject: [PATCH 056/260] adds performance enhancement to prevent merge conflicts --- Source/SwiftyJSON.swift | 21 +++++++++++---------- Tests/PerformanceTests.swift | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 5a69a106..5b0c16ff 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -478,8 +478,9 @@ extension JSON: Swift.ExpressibleByDictionaryLiteral { return JSON(dictionaryLiteral: initializeElement) } - self.init(elements.reduce([String : Any](minimumCapacity: elements.count)){(dictionary: [String : Any], element:(String, Any)) -> [String : Any] in - var d = dictionary + var dict = [String : Any](minimumCapacity: elements.count) + + for element in elements { let elementToSet: Any if let json = element.1 as? JSON { elementToSet = json.object @@ -493,9 +494,10 @@ extension JSON: Swift.ExpressibleByDictionaryLiteral { } else { elementToSet = element.1 } - d[element.0] = elementToSet - return d - } as Any) + dict[element.0] = elementToSet + } + + self.init(dict) } } @@ -626,12 +628,11 @@ extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { - - return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, Any)) -> [String : JSON] in - var d = dictionary - d[element.0] = JSON(element.1) - return d + var d = [String : JSON](minimumCapacity: rawDictionary.count) + for (key, value) in rawDictionary { + d[key] = JSON(value) } + return d } else { return nil } diff --git a/Tests/PerformanceTests.swift b/Tests/PerformanceTests.swift index 21b9b31f..34f94b8a 100644 --- a/Tests/PerformanceTests.swift +++ b/Tests/PerformanceTests.swift @@ -99,4 +99,24 @@ class PerformanceTests: XCTestCase { } } + func testLargeDictionaryMethodPerformance() { + var data: [String: JSON] = [:] + (0...100000).forEach { n in + data["\(n)"] = JSON([ + "name": "item\(n)", + "id": n + ]) + } + let json = JSON(data) + + self.measure() { + autoreleasepool{ + if let dictionary = json.dictionary { + XCTAssertTrue(dictionary.count > 0) + } else { + XCTFail("dictionary should not be nil") + } + } + } + } } From 39a19dc33c7cfa8927f81722d591643f12d80ba8 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Wed, 28 Sep 2016 22:45:19 +0800 Subject: [PATCH 057/260] Update Alamofire example for Swift3 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7cdedb6b..47de1278 100644 --- a/README.md +++ b/README.md @@ -401,10 +401,10 @@ SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: ```swift Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { - case .Success(let value): + case .success(let value): let json = JSON(value) print("JSON: \(json)") - case .Failure(let error): + case .failure(let error): print(error) } } From ff43c8e31b4a74e9f98ead17d9b83fa9caf6c486 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Thu, 29 Sep 2016 11:04:55 +0800 Subject: [PATCH 058/260] Auto tagging releases --- .travis.yml | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 14a93dd0..c65386a0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,24 @@ language: objective-c - osx_image: xcode8 xcode_sdk: iphonesimulator10.0 - -script: - - rvm get head # https://github.com/travis-ci/travis-ci/issues/6307 - - 'sh scripts/ci.sh' +env: + global: + - FRAMEWORK_NAME=SwiftyJSON +before_install: +- rvm get head +- brew update +- brew outdated carthage || brew upgrade carthage +before_deploy: +- carthage build --no-skip-current +- carthage archive $FRAMEWORK_NAME +script: +- sh scripts/ci.sh +deploy: + provider: releases + api_key: + secure: MufQRIzcHPU5fn9gyXl7kDGaLihN6zGABx9UWqNtkwq0AxV0aYNWys11nrKDIgoZFR+MbQHMoodpZK03yDdCLG03ncnOr3aytLOpI0imuDFWx16sieiVoYmnP5bfNFTN0qqXdfBy0OOsx4wO+F5Pwg5y1TgGYnKpXtEfdIU3Om4= + file: SwiftyJSON.framework.zip + skip_cleanup: true + on: + repo: SwiftyJSON/SwiftyJSON + tags: true From 522e74bf59874fb29b0a23206fb3f31e6d276d09 Mon Sep 17 00:00:00 2001 From: Jobins John Date: Mon, 3 Oct 2016 13:39:19 +0400 Subject: [PATCH 059/260] Copyright Year Update Copyright year updated in file header --- Example/Example/AppDelegate.swift | 2 +- Example/Example/ViewController.swift | 2 +- Source/SwiftyJSON.h | 2 +- Source/SwiftyJSON.swift | 62 ++++++++++++++++++---------- Tests/ArrayTests.swift | 2 +- Tests/ComparableTests.swift | 2 +- Tests/DictionaryTests.swift | 2 +- Tests/LiteralConvertibleTests.swift | 2 +- Tests/NumberTests.swift | 2 +- Tests/PerformanceTests.swift | 2 +- Tests/PrintableTests.swift | 2 +- Tests/RawRepresentableTests.swift | 2 +- Tests/RawTests.swift | 2 +- Tests/SequenceTypeTests.swift | 2 +- Tests/StringTests.swift | 2 +- Tests/SubscriptTests.swift | 2 +- 16 files changed, 56 insertions(+), 36 deletions(-) diff --git a/Example/Example/AppDelegate.swift b/Example/Example/AppDelegate.swift index 31b98b35..6c0aead8 100644 --- a/Example/Example/AppDelegate.swift +++ b/Example/Example/AppDelegate.swift @@ -1,6 +1,6 @@ // SwiftyJSON.h // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index 373be9bb..e12a4090 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -1,6 +1,6 @@ // SwiftyJSON.h // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Source/SwiftyJSON.h b/Source/SwiftyJSON.h index 74552a7c..ac942218 100644 --- a/Source/SwiftyJSON.h +++ b/Source/SwiftyJSON.h @@ -1,6 +1,6 @@ // SwiftyJSON.h // -// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang +// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 5b0c16ff..c489a0f5 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -1,6 +1,6 @@ // SwiftyJSON.swift // -// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang +// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -198,14 +198,17 @@ public struct JSON { public static var null: JSON { get { return JSON(NSNull()) } } } -public enum JSONIndex:Comparable { +public enum JSONIndex:Comparable +{ case array(Int) case dictionary(DictionaryIndex) case null } -public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { - switch (lhs, rhs) { +public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool +{ + switch (lhs, rhs) + { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): @@ -216,8 +219,10 @@ public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { } } -public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { - switch (lhs, rhs) { +public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool +{ + switch (lhs, rhs) + { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): @@ -228,12 +233,15 @@ public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { } -extension JSON: Collection{ +extension JSON: Collection +{ public typealias Index = JSONIndex - public var startIndex: Index{ - switch type { + public var startIndex: Index + { + switch type + { case .array: return .array(rawArray.startIndex) case .dictionary: @@ -243,8 +251,10 @@ extension JSON: Collection{ } } - public var endIndex: Index{ - switch type { + public var endIndex: Index + { + switch type + { case .array: return .array(rawArray.endIndex) case .dictionary: @@ -254,8 +264,10 @@ extension JSON: Collection{ } } - public func index(after i: Index) -> Index { - switch i { + public func index(after i: Index) -> Index + { + switch i + { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): @@ -266,8 +278,10 @@ extension JSON: Collection{ } - public subscript (position: Index) -> (String, JSON) { - switch position { + public subscript (position: Index) -> (String, JSON) + { + switch position + { case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): @@ -285,7 +299,8 @@ extension JSON: Collection{ /** * To mark both String and Int can be used in subscript. */ -public enum JSONKey { +public enum JSONKey +{ case index(Int) case key(String) } @@ -891,14 +906,19 @@ extension JSON { } } - public var int: Int? { - get { + public var int: Int? + { + get + { return self.number?.intValue } - set { - if let newValue = newValue { + set + { + if let newValue = newValue + { self.object = NSNumber(value: newValue) - } else { + } else + { self.object = NSNull() } } diff --git a/Tests/ArrayTests.swift b/Tests/ArrayTests.swift index 1c6b1ee4..e2d471a6 100644 --- a/Tests/ArrayTests.swift +++ b/Tests/ArrayTests.swift @@ -1,6 +1,6 @@ // ArrayTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/ComparableTests.swift b/Tests/ComparableTests.swift index 5ee2f072..53b7c231 100644 --- a/Tests/ComparableTests.swift +++ b/Tests/ComparableTests.swift @@ -1,6 +1,6 @@ // ComparableTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/DictionaryTests.swift b/Tests/DictionaryTests.swift index 12074ed3..13208ded 100644 --- a/Tests/DictionaryTests.swift +++ b/Tests/DictionaryTests.swift @@ -1,6 +1,6 @@ // DictionaryTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/LiteralConvertibleTests.swift b/Tests/LiteralConvertibleTests.swift index 1f6cf031..35abdf7d 100644 --- a/Tests/LiteralConvertibleTests.swift +++ b/Tests/LiteralConvertibleTests.swift @@ -1,6 +1,6 @@ // LiteralConvertibleTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/NumberTests.swift b/Tests/NumberTests.swift index e578bf83..54c48806 100644 --- a/Tests/NumberTests.swift +++ b/Tests/NumberTests.swift @@ -1,6 +1,6 @@ // NumberTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/PerformanceTests.swift b/Tests/PerformanceTests.swift index 34f94b8a..80b3c028 100644 --- a/Tests/PerformanceTests.swift +++ b/Tests/PerformanceTests.swift @@ -1,6 +1,6 @@ // PerformanceTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/PrintableTests.swift b/Tests/PrintableTests.swift index e9d38811..09c97781 100644 --- a/Tests/PrintableTests.swift +++ b/Tests/PrintableTests.swift @@ -1,6 +1,6 @@ // PrintableTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/RawRepresentableTests.swift b/Tests/RawRepresentableTests.swift index c4e79258..342cd782 100644 --- a/Tests/RawRepresentableTests.swift +++ b/Tests/RawRepresentableTests.swift @@ -1,6 +1,6 @@ // RawRepresentableTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/RawTests.swift b/Tests/RawTests.swift index 7ba7a334..1160726d 100644 --- a/Tests/RawTests.swift +++ b/Tests/RawTests.swift @@ -1,6 +1,6 @@ // RawTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SequenceTypeTests.swift b/Tests/SequenceTypeTests.swift index 3aae1c19..a9ff6cf6 100644 --- a/Tests/SequenceTypeTests.swift +++ b/Tests/SequenceTypeTests.swift @@ -1,7 +1,7 @@ // // SequenceTypeTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/StringTests.swift b/Tests/StringTests.swift index 8e720be4..1d46eb88 100644 --- a/Tests/StringTests.swift +++ b/Tests/StringTests.swift @@ -1,6 +1,6 @@ // StringTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SubscriptTests.swift b/Tests/SubscriptTests.swift index bdbd821a..66d5c20f 100644 --- a/Tests/SubscriptTests.swift +++ b/Tests/SubscriptTests.swift @@ -1,6 +1,6 @@ // SubscriptTests.swift // -// Copyright (c) 2014 Pinglin Tang +// Copyright (c) 2014 - 2016 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal From c7eedf9f4436e1b092238cb585cc441907d00d35 Mon Sep 17 00:00:00 2001 From: Jobins John Date: Mon, 3 Oct 2016 14:10:04 +0400 Subject: [PATCH 060/260] Copyright year upgraded --- Tests/BaseTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/BaseTests.swift b/Tests/BaseTests.swift index 7de2881d..b8a51a08 100644 --- a/Tests/BaseTests.swift +++ b/Tests/BaseTests.swift @@ -1,6 +1,6 @@ // BaseTests.swift // -// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang +// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal From 325529ec51675b029cf1af31eb84219b893c1fd7 Mon Sep 17 00:00:00 2001 From: Jobins John Date: Mon, 3 Oct 2016 14:10:19 +0400 Subject: [PATCH 061/260] Upgraded to swift 3.0 --- Example/Example/Base.lproj/LaunchScreen.xib | 4 ++-- SwiftyJSON.xcodeproj/project.pbxproj | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Example/Example/Base.lproj/LaunchScreen.xib b/Example/Example/Base.lproj/LaunchScreen.xib index b999ccb2..43a0234f 100644 --- a/Example/Example/Base.lproj/LaunchScreen.xib +++ b/Example/Example/Base.lproj/LaunchScreen.xib @@ -1,5 +1,5 @@ - + @@ -13,7 +13,7 @@ - - + @@ -79,4 +79,7 @@ + + + diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index e12a4090..db1d1da1 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -69,12 +69,7 @@ class ViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any!) { var nextController: UIViewController? - switch UIDevice.current.systemVersion.compare("8.0.0", options: NSString.CompareOptions.numeric) { - case .orderedSame, .orderedDescending: - nextController = (segue.destination as! UINavigationController).topViewController - case .orderedAscending: - nextController = segue.destination - } + nextController = segue.destination if let indexPath = self.tableView.indexPathForSelectedRow { let row = (indexPath as NSIndexPath).row From 32adaff4fa7628824fb658880b5053a45c70caa1 Mon Sep 17 00:00:00 2001 From: Giovanni Lodi Date: Thu, 13 Oct 2016 11:06:39 +1100 Subject: [PATCH 077/260] Explicitly set Prov Style Automatic for iOS target --- SwiftyJSON.xcodeproj/project.pbxproj | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 81a1e577..9b3d00bf 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -432,6 +432,7 @@ 2E4FEFDA19575BE100351305 = { CreatedOnToolsVersion = 6.0; LastSwiftMigration = 0800; + ProvisioningStyle = Automatic; }; 2E4FEFE519575BE100351305 = { CreatedOnToolsVersion = 6.0; @@ -744,7 +745,9 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -764,7 +767,9 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; From e81fb1c2585091a0b323e315b353cc22ad6985b0 Mon Sep 17 00:00:00 2001 From: Giovanni Lodi Date: Thu, 13 Oct 2016 11:07:21 +1100 Subject: [PATCH 078/260] Explictily set Prov Style Automatic for watchOS --- SwiftyJSON.xcodeproj/project.pbxproj | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 9b3d00bf..92fa4324 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -449,6 +449,9 @@ A8580F731BCF5C5B00DA927B = { CreatedOnToolsVersion = 7.1; }; + E4D7CCDE1B9465A700EE7221 = { + ProvisioningStyle = Automatic; + }; }; }; buildConfigurationList = 2E4FEFD519575BE100351305 /* Build configuration list for PBXProject "SwiftyJSON" */; @@ -989,7 +992,9 @@ APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -1012,7 +1017,9 @@ APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; From db404fca6c7562050b3e1bd30341dcb979211b90 Mon Sep 17 00:00:00 2001 From: Giovanni Lodi Date: Thu, 13 Oct 2016 11:07:45 +1100 Subject: [PATCH 079/260] Explicitly set Prov Style Automatic for tvOS --- SwiftyJSON.xcodeproj/project.pbxproj | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 92fa4324..840df705 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -440,6 +440,9 @@ ProvisioningStyle = Manual; TestTargetID = 2E4FEFDA19575BE100351305; }; + 7236B4EC1BAC14150020529B = { + ProvisioningStyle = Automatic; + }; 9C7DFC5A1A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; }; @@ -824,7 +827,9 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -846,7 +851,9 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; From 553610566ec6600a3db1cceb5efcd637897e4ce3 Mon Sep 17 00:00:00 2001 From: Giovanni Lodi Date: Fri, 21 Oct 2016 20:51:29 +1100 Subject: [PATCH 080/260] Explictily set Prov Style Automatic for macOS --- SwiftyJSON.xcodeproj/project.pbxproj | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 840df705..b254f287 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -445,6 +445,7 @@ }; 9C7DFC5A1A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; + ProvisioningStyle = Automatic; }; 9C7DFC641A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; @@ -874,7 +875,7 @@ isa = XCBuildConfiguration; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; - CODE_SIGN_IDENTITY = ""; + CODE_SIGN_IDENTITY = "Mac Developer"; COMBINE_HIDPI_IMAGES = YES; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; @@ -902,7 +903,7 @@ isa = XCBuildConfiguration; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; - CODE_SIGN_IDENTITY = ""; + CODE_SIGN_IDENTITY = "Mac Developer"; COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; From 5b7400f279122871095ffbdbfe6c913ecda6b14e Mon Sep 17 00:00:00 2001 From: Jeff Kang Date: Fri, 28 Oct 2016 16:46:34 +0900 Subject: [PATCH 081/260] Add getting a string using a path to the element. --- Example/Playground.playground/Contents.swift | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Example/Playground.playground/Contents.swift b/Example/Playground.playground/Contents.swift index bfe9c3e6..5ccdfcce 100644 --- a/Example/Playground.playground/Contents.swift +++ b/Example/Playground.playground/Contents.swift @@ -77,3 +77,22 @@ print(arrayOfString) // Getting a string from a JSON Dictionary jsonDictionary["country"].stringValue +//Getting a string using a path to the element +let path: [JSONSubscriptType] = ["users", 1, "info", "name"] +let feed = jsonArray[path].string + +////Just the same +//let name = json[1]["list"][2]["name"].string +////Alternatively +//let name = json[1,"list",2,"name"].string +// +// +//```swift +////With a hard way +//let name = json[].string +//``` +//```swift +////With a custom way +//let keys:[SubscriptType] = [1,"list",2,"name"] +//let name = json[keys].string +//``` From 1dbcdaed717cd85f01aba0c0d1c576bcb790aefa Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Fri, 28 Oct 2016 17:40:58 +0800 Subject: [PATCH 082/260] Fix examples in README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 34f12b82..5cc5c24d 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ let name = json["name"].stringValue ``` ```swift //Getting a string using a path to the element -let path = [1,"list",2,"name"] +let path: [JSONSubscriptType] = [1,"list",2,"name"] let name = json[path].string //Just the same let name = json[1]["list"][2]["name"].string @@ -401,7 +401,7 @@ json["address"] = "L.A." // Add the "address": "L.A." in json var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] json["list"][3]["what"] = "that" json["list",3,"what"] = "that" -let path = ["list",3,"what"] +let path: [JSONSubscriptType] = ["list",3,"what"] json[path] = "that" ``` ```swift From 3e54d90db10335c428405cf96b4ac4e407607ac5 Mon Sep 17 00:00:00 2001 From: mc1024 Date: Fri, 28 Oct 2016 16:38:17 -0400 Subject: [PATCH 083/260] Fix warning In XCode 8.1 (8B62) Expression implicitly coerced from 'String?' to Any --- Source/SwiftyJSON.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 7e71a187..3e9c3266 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -856,7 +856,7 @@ extension JSON { } } set { - self.object = newValue?.absoluteString + self.object = newValue?.absoluteString ?? NSNull() } } } From 9f5cfa06ec279bcab828d2e7856ca40b00c2a1dc Mon Sep 17 00:00:00 2001 From: Giovanni Lodi Date: Thu, 13 Oct 2016 11:06:39 +1100 Subject: [PATCH 084/260] Explicitly set Prov Style Automatic for iOS target --- SwiftyJSON.xcodeproj/project.pbxproj | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index f3fa05ab..e3ced065 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -432,6 +432,7 @@ 2E4FEFDA19575BE100351305 = { CreatedOnToolsVersion = 6.0; LastSwiftMigration = 0800; + ProvisioningStyle = Automatic; }; 2E4FEFE519575BE100351305 = { CreatedOnToolsVersion = 6.0; @@ -748,8 +749,9 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -769,8 +771,9 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; From e7b7e26dc75ae38caafc80ed8802885163424350 Mon Sep 17 00:00:00 2001 From: Giovanni Lodi Date: Thu, 13 Oct 2016 11:07:21 +1100 Subject: [PATCH 085/260] Explictily set Prov Style Automatic for watchOS --- SwiftyJSON.xcodeproj/project.pbxproj | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index e3ced065..23ed1cda 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -449,6 +449,9 @@ A8580F731BCF5C5B00DA927B = { CreatedOnToolsVersion = 7.1; }; + E4D7CCDE1B9465A700EE7221 = { + ProvisioningStyle = Automatic; + }; }; }; buildConfigurationList = 2E4FEFD519575BE100351305 /* Build configuration list for PBXProject "SwiftyJSON" */; @@ -995,8 +998,13 @@ APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; CODE_SIGN_IDENTITY = "iPhone Developer"; +<<<<<<< HEAD "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; +======= + "CODE_SIGN_IDENTITY[sdk=watchos*]" = "iPhone Developer"; +>>>>>>> Explictily set Prov Style Automatic for watchOS DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -1019,8 +1027,13 @@ APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; CODE_SIGN_IDENTITY = "iPhone Developer"; +<<<<<<< HEAD "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; +======= + "CODE_SIGN_IDENTITY[sdk=watchos*]" = "iPhone Developer"; +>>>>>>> Explictily set Prov Style Automatic for watchOS DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; From 423bdc0f2adbcb39c314b85bcd8ce027e335eb53 Mon Sep 17 00:00:00 2001 From: Giovanni Lodi Date: Thu, 13 Oct 2016 11:07:45 +1100 Subject: [PATCH 086/260] Explicitly set Prov Style Automatic for tvOS --- SwiftyJSON.xcodeproj/project.pbxproj | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 23ed1cda..33353551 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -440,6 +440,9 @@ ProvisioningStyle = Manual; TestTargetID = 2E4FEFDA19575BE100351305; }; + 7236B4EC1BAC14150020529B = { + ProvisioningStyle = Automatic; + }; 9C7DFC5A1A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; }; @@ -828,8 +831,9 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -851,8 +855,9 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer"; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -998,11 +1003,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; CODE_SIGN_IDENTITY = "iPhone Developer"; -<<<<<<< HEAD - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; -======= "CODE_SIGN_IDENTITY[sdk=watchos*]" = "iPhone Developer"; ->>>>>>> Explictily set Prov Style Automatic for watchOS DEFINES_MODULE = YES; DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; @@ -1027,11 +1028,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; CODE_SIGN_IDENTITY = "iPhone Developer"; -<<<<<<< HEAD - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; -======= "CODE_SIGN_IDENTITY[sdk=watchos*]" = "iPhone Developer"; ->>>>>>> Explictily set Prov Style Automatic for watchOS DEFINES_MODULE = YES; DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; From eadd072159f1626c060cc69711ffa45bb04f6e98 Mon Sep 17 00:00:00 2001 From: Giovanni Lodi Date: Fri, 21 Oct 2016 20:51:29 +1100 Subject: [PATCH 087/260] Explictily set Prov Style Automatic for macOS --- SwiftyJSON.xcodeproj/project.pbxproj | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 33353551..d940cb1e 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -445,6 +445,7 @@ }; 9C7DFC5A1A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; + ProvisioningStyle = Automatic; }; 9C7DFC641A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; @@ -878,7 +879,7 @@ isa = XCBuildConfiguration; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; - CODE_SIGN_IDENTITY = ""; + CODE_SIGN_IDENTITY = "Mac Developer"; COMBINE_HIDPI_IMAGES = YES; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; @@ -906,7 +907,7 @@ isa = XCBuildConfiguration; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; - CODE_SIGN_IDENTITY = ""; + CODE_SIGN_IDENTITY = "Mac Developer"; COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; From 58fad8a2f19701069222029a16a6e927330a8b67 Mon Sep 17 00:00:00 2001 From: Jeff Kang Date: Mon, 31 Oct 2016 15:57:47 +0900 Subject: [PATCH 088/260] Finish subscript part. Add descriptions. --- Example/Playground.playground/Contents.swift | 44 ++++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/Example/Playground.playground/Contents.swift b/Example/Playground.playground/Contents.swift index 5ccdfcce..90b99433 100644 --- a/Example/Playground.playground/Contents.swift +++ b/Example/Playground.playground/Contents.swift @@ -1,9 +1,15 @@ //: Playground - noun: a place where people can play - /*: - ## Basic setting for playground + # SwiftyJSON + SwiftyJSON makes it easy to deal with JSON data in Swift. + + You must have to build `SwiftyJSON iOS` package for import. + */ +/*: + ### Basic setting for playground */ import SwiftyJSON +import Foundation var jsonData: Data? @@ -18,9 +24,9 @@ let jsonObject = try JSONSerialization.jsonObject(with: jsonData!, options: .all let jsonString = String(data: jsonData!, encoding: .utf8) /*: - # Usage + ## Usage - ## Initialization + ### Initialization */ import SwiftyJSON @@ -37,7 +43,7 @@ let dataFromString = jsonString?.data(using: .utf8) let json3 = JSON(data: dataFromString!) /*: - ## Subscript + ### Subscript */ // Example json var jsonArray: JSON = [ @@ -78,21 +84,15 @@ print(arrayOfString) jsonDictionary["country"].stringValue //Getting a string using a path to the element -let path: [JSONSubscriptType] = ["users", 1, "info", "name"] -let feed = jsonArray[path].string +let path = ["users", 1, "info", "name"] as [JSONSubscriptType] +var name = jsonArray["users",1,"info","name"].string + +//With a custom way +let keys: [JSONSubscriptType] = ["users", 1, "info", "name"] +name = jsonArray[keys].string + +//Just the same +name = jsonArray["users"][1]["info"]["name"].string -////Just the same -//let name = json[1]["list"][2]["name"].string -////Alternatively -//let name = json[1,"list",2,"name"].string -// -// -//```swift -////With a hard way -//let name = json[].string -//``` -//```swift -////With a custom way -//let keys:[SubscriptType] = [1,"list",2,"name"] -//let name = json[keys].string -//``` +//Alternatively +name = jsonArray["users",1,"info","name"].string \ No newline at end of file From e2be46e1656f64ba264f0f87c50cf4ce1b15a9ff Mon Sep 17 00:00:00 2001 From: Jeff Kang Date: Mon, 31 Oct 2016 16:06:13 +0900 Subject: [PATCH 089/260] Turn on render documentation mode. --- Example/Playground.playground/contents.xcplayground | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Example/Playground.playground/contents.xcplayground b/Example/Playground.playground/contents.xcplayground index 35968656..89da2d47 100644 --- a/Example/Playground.playground/contents.xcplayground +++ b/Example/Playground.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file From da5c307822dc54e7ab23a5e4192f13c72ceb22d8 Mon Sep 17 00:00:00 2001 From: Jeff Kang Date: Mon, 31 Oct 2016 16:29:37 +0900 Subject: [PATCH 090/260] Fix syntax. --- README.md | 50 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 5cc5c24d..84570529 100644 --- a/README.md +++ b/README.md @@ -33,13 +33,11 @@ Take the Twitter API for example. Say we want to retrieve a user's "name" value The code would look like this: ```swift - if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: AnyObject]], let user = statusesArray[0]["user"] as? [String: AnyObject], let username = user["name"] as? String { // Finally we got the username } - ``` It's not good. @@ -47,30 +45,26 @@ It's not good. Even if we use optional chaining, it would be messy: ```swift - if let JSONObject = try JSONSerialization.jsonObject(with: data,, options: .allowFragments) as? [[String: AnyObject]], let username = (JSONObject[0]["user"] as? [String: AnyObject])?["name"] as? String { // There's our username } - ``` + An unreadable mess--for something that should really be simple! With SwiftyJSON all you have to do is: ```swift - let json = JSON(data: dataFromNetworking) if let userName = json[0]["user"]["name"].string { //Now you got your value } - ``` And don't worry about the Optional Wrapping thing. It's done for you automatically. ```swift - let json = JSON(data: dataFromNetworking) if let userName = json[999999]["wrong_key"]["wrong_name"].string { //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety @@ -78,7 +72,6 @@ if let userName = json[999999]["wrong_key"]["wrong_name"].string { //Print the error print(json[999999]["wrong_key"]["wrong_name"]) } - ``` ## Requirements @@ -91,6 +84,7 @@ if let userName = json[999999]["wrong_key"]["wrong_name"].string { #### CocoaPods (iOS 8+, OS X 10.9+) You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON`by adding it to your `Podfile`: + ```ruby platform :ios, '8.0' use_frameworks! @@ -99,12 +93,14 @@ target 'MyApp' do pod 'SwiftyJSON' end ``` + Note that this requires CocoaPods version 36, and your iOS deployment target to be at least 8.0: #### Carthage (iOS 8+, OS X 10.9+) You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: + ``` github "SwiftyJSON/SwiftyJSON" ``` @@ -112,6 +108,7 @@ github "SwiftyJSON/SwiftyJSON" #### Swift Package Manager You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: + ```swift import PackageDescription @@ -140,12 +137,15 @@ To use this library in your project manually you may: ```swift import SwiftyJSON ``` + ```swift let json = JSON(data: dataFromNetworking) ``` + ```swift let json = JSON(jsonObject) ``` + ```swift if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) { let json = JSON(data: dataFromString) @@ -168,6 +168,7 @@ let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue}) //Getting a string from a JSON Dictionary let name = json["name"].stringValue ``` + ```swift //Getting a string using a path to the element let path: [JSONSubscriptType] = [1,"list",2,"name"] @@ -177,10 +178,12 @@ let name = json[1]["list"][2]["name"].string //Alternatively let name = json[1,"list",2,"name"].string ``` + ```swift //With a hard way let name = json[].string ``` + ```swift //With a custom way let keys:[SubscriptType] = [1,"list",2,"name"] @@ -195,7 +198,9 @@ for (key,subJson):(String, JSON) in json { //Do something you want } ``` + *The first element is always a String, even if the JSON is an Array* + ```swift //If json is .Array //The `index` is 0.. = json["list"].arrayValue ``` + ```swift //If not a Dictionary or nil, return [:] let user: Dictionary = json["user"].dictionaryValue @@ -314,6 +328,7 @@ let user: Dictionary = json["user"].dictionaryValue json["name"] = JSON("new-name") json[0] = JSON(1) ``` + ```swift json["id"].int = 1234567890 json["coordinate"].double = 8766.766 @@ -327,15 +342,18 @@ json.dictionaryObject = ["name":"Jack", "age":25] ```swift let jsonObject: AnyObject = json.object ``` + ```swift if let jsonObject: AnyObject = json.rawValue ``` + ```swift //convert the JSON to raw NSData if let data = json.rawData() { //Do something you want } ``` + ```swift //convert the JSON to a raw String if let string = json.rawString() { @@ -353,34 +371,42 @@ if json["name"].exists() #### Literal convertibles For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) + ```swift //StringLiteralConvertible let json: JSON = "I'm a json" ``` + ```swift //IntegerLiteralConvertible let json: JSON = 12345 ``` + ```swift //BooleanLiteralConvertible let json: JSON = true ``` + ```swift //FloatLiteralConvertible let json: JSON = 2.8765 ``` + ```swift //DictionaryLiteralConvertible let json: JSON = ["I":"am", "a":"json"] ``` + ```swift //ArrayLiteralConvertible let json: JSON = ["I", "am", "a", "json"] ``` + ```swift //NilLiteralConvertible let json: JSON = nil ``` + ```swift //With subscript in array var json: JSON = [1,2,3] @@ -389,6 +415,7 @@ json[1] = 200 json[2] = 300 json[999] = 300 //Don't worry, nothing will happen ``` + ```swift //With subscript in dictionary var json: JSON = ["name": "Jack", "age": 25] @@ -396,6 +423,7 @@ json["name"] = "Mike" json["age"] = "25" //It's OK to set String json["address"] = "L.A." // Add the "address": "L.A." in json ``` + ```swift //Array & Dictionary var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] @@ -404,6 +432,7 @@ json["list",3,"what"] = "that" let path: [JSONSubscriptType] = ["list",3,"what"] json[path] = "that" ``` + ```swift //With other JSON objects let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] @@ -411,11 +440,12 @@ let auth: JSON = [ "user": user.object //use user.object instead of just user "apikey": "supersecretapitoken" ] -```` +``` -##Work with Alamofire +## Work with Alamofire SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: + ```swift Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { From ef668d869f7cbbb54419d7fbf4b981de4ac3c651 Mon Sep 17 00:00:00 2001 From: Sam Agnew Date: Fri, 4 Nov 2016 14:27:36 -0400 Subject: [PATCH 091/260] Fix typo in README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 84570529..4fa31853 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ let package = Package( ) ``` -Note that the [Swift Package Manager](https://swift.org/package-manager) is still in early design and development, for more infomation checkout its [GitHub Page](https://github.com/apple/swift-package-manager) +Note that the [Swift Package Manager](https://swift.org/package-manager) is still in early design and development, for more information checkout its [GitHub Page](https://github.com/apple/swift-package-manager) #### Manually (iOS 7+, OS X 10.9+) From 2c9f373d53e5a5f4fc4eb6e81c089505507719a7 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Mon, 7 Nov 2016 00:17:25 +0800 Subject: [PATCH 092/260] Re-organize tests to satisfy SPM --- SwiftyJSON.xcodeproj/project.pbxproj | 19 ++++++++++--------- Tests/{ => SwiftyJSONTests}/ArrayTests.swift | 0 Tests/{ => SwiftyJSONTests}/BaseTests.swift | 0 .../ComparableTests.swift | 0 .../DictionaryTests.swift | 0 Tests/{ => SwiftyJSONTests}/Info-OSX.plist | 0 Tests/{ => SwiftyJSONTests}/Info-iOS.plist | 0 Tests/{ => SwiftyJSONTests}/Info-tvOS.plist | 0 .../LiteralConvertibleTests.swift | 0 .../NestedJSONTests.swift | 0 Tests/{ => SwiftyJSONTests}/NumberTests.swift | 0 .../PerformanceTests.swift | 0 .../PrintableTests.swift | 0 .../RawRepresentableTests.swift | 0 Tests/{ => SwiftyJSONTests}/RawTests.swift | 0 .../SequenceTypeTests.swift | 0 Tests/{ => SwiftyJSONTests}/StringTests.swift | 0 .../SubscriptTests.swift | 0 Tests/{ => SwiftyJSONTests}/Tests.json | 0 19 files changed, 10 insertions(+), 9 deletions(-) rename Tests/{ => SwiftyJSONTests}/ArrayTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/BaseTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/ComparableTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/DictionaryTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/Info-OSX.plist (100%) rename Tests/{ => SwiftyJSONTests}/Info-iOS.plist (100%) rename Tests/{ => SwiftyJSONTests}/Info-tvOS.plist (100%) rename Tests/{ => SwiftyJSONTests}/LiteralConvertibleTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/NestedJSONTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/NumberTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/PerformanceTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/PrintableTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/RawRepresentableTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/RawTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/SequenceTypeTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/StringTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/SubscriptTests.swift (100%) rename Tests/{ => SwiftyJSONTests}/Tests.json (100%) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index d940cb1e..4bddfa14 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -183,7 +183,7 @@ isa = PBXGroup; children = ( 2E4FEFDD19575BE100351305 /* Source */, - 2E4FEFEA19575BE100351305 /* Tests */, + 2E4FEFEA19575BE100351305 /* SwiftyJSONTests */, 2E4FEFDC19575BE100351305 /* Products */, ); sourceTree = ""; @@ -223,7 +223,7 @@ name = "Supporting Files"; sourceTree = ""; }; - 2E4FEFEA19575BE100351305 /* Tests */ = { + 2E4FEFEA19575BE100351305 /* SwiftyJSONTests */ = { isa = PBXGroup; children = ( A885D1DA19CFCFF0002FD4C3 /* Tests.json */, @@ -243,7 +243,8 @@ A8B66C8D19E52F4200540692 /* ArrayTests.swift */, 2E4FEFEB19575BE100351305 /* Supporting Files */, ); - path = Tests; + name = SwiftyJSONTests; + path = Tests/SwiftyJSONTests; sourceTree = ""; }; 2E4FEFEB19575BE100351305 /* Supporting Files */ = { @@ -804,7 +805,7 @@ "DEBUG=1", "$(inherited)", ); - INFOPLIST_FILE = "Tests/Info-iOS.plist"; + INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-iOS.plist"; IPHONEOS_DEPLOYMENT_TARGET = 9.1; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; METAL_ENABLE_DEBUG_INFO = YES; @@ -818,7 +819,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; DEVELOPMENT_TEAM = ""; - INFOPLIST_FILE = "Tests/Info-iOS.plist"; + INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-iOS.plist"; IPHONEOS_DEPLOYMENT_TARGET = 9.1; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; METAL_ENABLE_DEBUG_INFO = NO; @@ -938,7 +939,7 @@ "DEBUG=1", "$(inherited)", ); - INFOPLIST_FILE = "Tests/Info-OSX.plist"; + INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-OSX.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = YES; @@ -955,7 +956,7 @@ COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; FRAMEWORK_SEARCH_PATHS = ""; - INFOPLIST_FILE = "Tests/Info-OSX.plist"; + INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-OSX.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = NO; @@ -971,7 +972,7 @@ CODE_SIGN_IDENTITY = ""; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Tests/Info-tvOS.plist"; + INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-tvOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.tangplin.SwiftyJSON-tvOS-Tests"; @@ -988,7 +989,7 @@ COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; - INFOPLIST_FILE = "Tests/Info-tvOS.plist"; + INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-tvOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.tangplin.SwiftyJSON-tvOS-Tests"; diff --git a/Tests/ArrayTests.swift b/Tests/SwiftyJSONTests/ArrayTests.swift similarity index 100% rename from Tests/ArrayTests.swift rename to Tests/SwiftyJSONTests/ArrayTests.swift diff --git a/Tests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift similarity index 100% rename from Tests/BaseTests.swift rename to Tests/SwiftyJSONTests/BaseTests.swift diff --git a/Tests/ComparableTests.swift b/Tests/SwiftyJSONTests/ComparableTests.swift similarity index 100% rename from Tests/ComparableTests.swift rename to Tests/SwiftyJSONTests/ComparableTests.swift diff --git a/Tests/DictionaryTests.swift b/Tests/SwiftyJSONTests/DictionaryTests.swift similarity index 100% rename from Tests/DictionaryTests.swift rename to Tests/SwiftyJSONTests/DictionaryTests.swift diff --git a/Tests/Info-OSX.plist b/Tests/SwiftyJSONTests/Info-OSX.plist similarity index 100% rename from Tests/Info-OSX.plist rename to Tests/SwiftyJSONTests/Info-OSX.plist diff --git a/Tests/Info-iOS.plist b/Tests/SwiftyJSONTests/Info-iOS.plist similarity index 100% rename from Tests/Info-iOS.plist rename to Tests/SwiftyJSONTests/Info-iOS.plist diff --git a/Tests/Info-tvOS.plist b/Tests/SwiftyJSONTests/Info-tvOS.plist similarity index 100% rename from Tests/Info-tvOS.plist rename to Tests/SwiftyJSONTests/Info-tvOS.plist diff --git a/Tests/LiteralConvertibleTests.swift b/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift similarity index 100% rename from Tests/LiteralConvertibleTests.swift rename to Tests/SwiftyJSONTests/LiteralConvertibleTests.swift diff --git a/Tests/NestedJSONTests.swift b/Tests/SwiftyJSONTests/NestedJSONTests.swift similarity index 100% rename from Tests/NestedJSONTests.swift rename to Tests/SwiftyJSONTests/NestedJSONTests.swift diff --git a/Tests/NumberTests.swift b/Tests/SwiftyJSONTests/NumberTests.swift similarity index 100% rename from Tests/NumberTests.swift rename to Tests/SwiftyJSONTests/NumberTests.swift diff --git a/Tests/PerformanceTests.swift b/Tests/SwiftyJSONTests/PerformanceTests.swift similarity index 100% rename from Tests/PerformanceTests.swift rename to Tests/SwiftyJSONTests/PerformanceTests.swift diff --git a/Tests/PrintableTests.swift b/Tests/SwiftyJSONTests/PrintableTests.swift similarity index 100% rename from Tests/PrintableTests.swift rename to Tests/SwiftyJSONTests/PrintableTests.swift diff --git a/Tests/RawRepresentableTests.swift b/Tests/SwiftyJSONTests/RawRepresentableTests.swift similarity index 100% rename from Tests/RawRepresentableTests.swift rename to Tests/SwiftyJSONTests/RawRepresentableTests.swift diff --git a/Tests/RawTests.swift b/Tests/SwiftyJSONTests/RawTests.swift similarity index 100% rename from Tests/RawTests.swift rename to Tests/SwiftyJSONTests/RawTests.swift diff --git a/Tests/SequenceTypeTests.swift b/Tests/SwiftyJSONTests/SequenceTypeTests.swift similarity index 100% rename from Tests/SequenceTypeTests.swift rename to Tests/SwiftyJSONTests/SequenceTypeTests.swift diff --git a/Tests/StringTests.swift b/Tests/SwiftyJSONTests/StringTests.swift similarity index 100% rename from Tests/StringTests.swift rename to Tests/SwiftyJSONTests/StringTests.swift diff --git a/Tests/SubscriptTests.swift b/Tests/SwiftyJSONTests/SubscriptTests.swift similarity index 100% rename from Tests/SubscriptTests.swift rename to Tests/SwiftyJSONTests/SubscriptTests.swift diff --git a/Tests/Tests.json b/Tests/SwiftyJSONTests/Tests.json similarity index 100% rename from Tests/Tests.json rename to Tests/SwiftyJSONTests/Tests.json From 2eb271f87a251577b20add3f6954ba447f512f76 Mon Sep 17 00:00:00 2001 From: Simon Tsai Date: Thu, 10 Nov 2016 08:06:27 -0500 Subject: [PATCH 093/260] =?UTF-8?q?The=20=E2=80=98isBool=E2=80=99=20functi?= =?UTF-8?q?on=20on=20the=20NSNumber=20extension=20uses=20=E2=80=98trueObjC?= =?UTF-8?q?Type=E2=80=99,=20which=20represents=20the=20type=20encoding=20f?= =?UTF-8?q?or=20=E2=80=98true=E2=80=99=20represented=20as=20an=20NSNumber,?= =?UTF-8?q?=20and=20=E2=80=98falseObjCType=E2=80=99,=20which=20represents?= =?UTF-8?q?=20the=20type=20encoding=20for=20=E2=80=98false=E2=80=99=20repr?= =?UTF-8?q?esented=20as=20an=20NSNumber.=20Both=20type=20encodings=20are?= =?UTF-8?q?=20equal=20to=20=E2=80=98c=E2=80=99.=20However,=20an=20NSNumber?= =?UTF-8?q?=20that=20wraps=20around=20a=20value=20of=20type=20Int8=20also?= =?UTF-8?q?=20has=20a=20type=20encoding=20of=20=E2=80=98c=E2=80=99.=20Ther?= =?UTF-8?q?efore,=20a=20user=20who=20passes=20in=20a=20value=20of=200=20or?= =?UTF-8?q?=201=20(of=20type=20Int8)=20into=20JSON=20will=20expect=20to=20?= =?UTF-8?q?see=20the=20numbers=200=20or=201=20as=20the=20output=20because?= =?UTF-8?q?=20that=20was=20the=20intent.=20Unfortunately,=20that=20value?= =?UTF-8?q?=20will=20be=20wrapped=20into=20NSNumber=20and=20be=20considere?= =?UTF-8?q?d=20a=20bool,=20so=20the=20user=20will=20see=20=E2=80=98true?= =?UTF-8?q?=E2=80=99=20or=20=E2=80=98false=E2=80=99=20instead.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Therefore, when setting a new value of type Int8 on the computed properties ‘int8’ or ‘int8Value’, the new value should be used to directly set ‘object’, which should then check for the Int8 type and use an Int instead. This is fine because an Int8 converted to an Int will always work and retain the same behavior of JSON, and also because the user’s intent is to use a number, not a boolean. Having said that, the tests for Int8 don’t test the right thing. The user’s intent is to use an integer, which is a number. However, the test assumes hardware implementation and accepts the fact that it can either be true or a number, which is unintuitive. Int8 is a pragmatic refinement to the semantic meaning of an integer, and should therefore be used as a number like the user intends, not a boolean. --- Source/SwiftyJSON.swift | 7 +++++-- Tests/SwiftyJSONTests/NumberTests.swift | 12 ++---------- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 3e9c3266..4aa6fcc7 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -157,6 +157,9 @@ public struct JSON { set { _error = nil switch newValue { + case let int8Value as Int8 where type(of: newValue) == Int8.self: + _type = .number + self.rawNumber = NSNumber(value: Int(int8Value)) case let number as NSNumber: if number.isBool { _type = .bool @@ -964,7 +967,7 @@ extension JSON { } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + self.object = newValue } else { self.object = NSNull() } @@ -976,7 +979,7 @@ extension JSON { return self.numberValue.int8Value } set { - self.object = NSNumber(value: newValue) + self.object = newValue } } diff --git a/Tests/SwiftyJSONTests/NumberTests.swift b/Tests/SwiftyJSONTests/NumberTests.swift index 54c48806..37e89cc8 100644 --- a/Tests/SwiftyJSONTests/NumberTests.swift +++ b/Tests/SwiftyJSONTests/NumberTests.swift @@ -192,11 +192,7 @@ class NumberTests: XCTestCase { print(json.number) XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) - #if (arch(x86_64) || arch(arm64)) - XCTAssertEqual(json.stringValue, "false") - #elseif (arch(i386) || arch(arm)) - XCTAssertEqual(json.stringValue, "0") - #endif + XCTAssertEqual(json.stringValue, "0") let n1 = NSNumber(value: 1 as Int8) @@ -205,11 +201,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.int8Value == n1.int8Value) XCTAssertTrue(json.number! == n1) XCTAssertEqual(json.numberValue, n1) - #if (arch(x86_64) || arch(arm64)) - XCTAssertEqual(json.stringValue, "true") - #elseif (arch(i386) || arch(arm)) - XCTAssertEqual(json.stringValue, "1") - #endif + XCTAssertEqual(json.stringValue, "1") } func testUInt8() { From 6f0ddada0be966886a67884e9be70bbdc005b1c0 Mon Sep 17 00:00:00 2001 From: skyline75489 Date: Sun, 13 Nov 2016 17:19:17 +0800 Subject: [PATCH 094/260] Fix 'AnyObject' in comment and README.md --- README.md | 12 ++++++------ Source/SwiftyJSON.swift | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 4fa31853..0f29db0b 100644 --- a/README.md +++ b/README.md @@ -33,8 +33,8 @@ Take the Twitter API for example. Say we want to retrieve a user's "name" value The code would look like this: ```swift -if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: AnyObject]], - let user = statusesArray[0]["user"] as? [String: AnyObject], +if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], + let user = statusesArray[0]["user"] as? [String: Any], let username = user["name"] as? String { // Finally we got the username } @@ -45,8 +45,8 @@ It's not good. Even if we use optional chaining, it would be messy: ```swift -if let JSONObject = try JSONSerialization.jsonObject(with: data,, options: .allowFragments) as? [[String: AnyObject]], - let username = (JSONObject[0]["user"] as? [String: AnyObject])?["name"] as? String { +if let JSONObject = try JSONSerialization.jsonObject(with: data,, options: .allowFragments) as? [[String: Any]], + let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String { // There's our username } ``` @@ -340,11 +340,11 @@ json.dictionaryObject = ["name":"Jack", "age":25] #### Raw object ```swift -let jsonObject: AnyObject = json.object +let jsonObject: Any = json.object ``` ```swift -if let jsonObject: AnyObject = json.rawValue +if let jsonObject: Any = json.rawValue ``` ```swift diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 3e9c3266..48464179 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -617,7 +617,7 @@ extension JSON { } } - //Optional [AnyObject] + //Optional [Any] public var arrayObject: [Any]? { get { switch self.type { @@ -659,7 +659,7 @@ extension JSON { return self.dictionary ?? [:] } - //Optional [String : AnyObject] + //Optional [String : Any] public var dictionaryObject: [String : Any]? { get { switch self.type { From d983bd9cc9b9b9e8b19ddad5f02612ae6d343101 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Wed, 16 Nov 2016 23:01:12 +0800 Subject: [PATCH 095/260] Attemp to fix #697 --- Source/SwiftyJSON.swift | 301 ++++++++++++++++++++++------------------ 1 file changed, 169 insertions(+), 132 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 3e9c3266..6034a6b9 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -38,11 +38,11 @@ public let ErrorInvalidJSON: Int = 490 /** JSON's type definitions. - + See http://www.json.org */ public enum Type :Int{ - + case number case string case bool @@ -54,14 +54,14 @@ public enum Type :Int{ // MARK: - JSON Base public struct JSON { - + /** Creates a JSON using the data. - + - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: The NSErrorPointer used to return the error. `nil` by default. - + - returns: The created JSON */ public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { @@ -75,45 +75,45 @@ public struct JSON { self.init(NSNull()) } } - + /** Creates a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - + - returns: The created JSON */ public static func parse(_ string:String) -> JSON { return string.data(using: String.Encoding.utf8) .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) } - + /** Creates a JSON using the object. - + - 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. - + - returns: The created JSON */ public init(_ object: Any) { self.object = object } - + /** Creates a JSON from a [JSON] - + - parameter jsonArray: A Swift array of JSON objects - + - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } - + /** Creates a JSON from a [String: JSON] - + - parameter jsonDictionary: A Swift dictionary of JSON objects - + - returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { @@ -123,7 +123,7 @@ public struct JSON { } self.init(dictionary) } - + /// Private object fileprivate var rawArray: [Any] = [] fileprivate var rawDictionary: [String : Any] = [:] @@ -135,7 +135,7 @@ public struct JSON { fileprivate var _type: Type = .null /// prviate error fileprivate var _error: NSError? = nil - + /// Object in JSON public var object: Any { get { @@ -185,13 +185,13 @@ public struct JSON { } } } - + /// JSON type public var type: Type { get { return _type } } - + /// Error in JSON public var error: NSError? { get { return self._error } } - + /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } @@ -203,41 +203,77 @@ public enum JSONIndex:Comparable case array(Int) case dictionary(DictionaryIndex) case null -} -public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool -{ - switch (lhs, rhs) + static public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { - case (.array(let left), .array(let right)): - return left == right - case (.dictionary(let left), .dictionary(let right)): - return left == right - case (.null, .null): return true - default: - return false + switch (lhs, rhs) + { + case (.array(let left), .array(let right)): + return left == right + case (.dictionary(let left), .dictionary(let right)): + return left == right + case (.null, .null): return true + default: + return false + } + } + + static public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool + { + switch (lhs, rhs) + { + case (.array(let left), .array(let right)): + return left < right + case (.dictionary(let left), .dictionary(let right)): + return left < right + default: + return false + } } + } -public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool +public enum JSONRawIndex: Comparable { - switch (lhs, rhs) + case array(Int) + case dictionary(DictionaryIndex) + case null + + static public func ==(lhs: JSONRawIndex, rhs: JSONRawIndex) -> Bool { - case (.array(let left), .array(let right)): - return left < right - case (.dictionary(let left), .dictionary(let right)): - return left < right - default: - return false + switch (lhs, rhs) + { + case (.array(let left), .array(let right)): + return left == right + case (.dictionary(let left), .dictionary(let right)): + return left == right + case (.null, .null): return true + default: + return false + } } -} + static public func <(lhs: JSONRawIndex, rhs: JSONRawIndex) -> Bool + { + switch (lhs, rhs) + { + case (.array(let left), .array(let right)): + return left < right + case (.dictionary(let left), .dictionary(let right)): + return left < right + default: + return false + } + } + + +} extension JSON: Collection { - - public typealias Index = JSONIndex - + + public typealias Index = JSONRawIndex + public var startIndex: Index { switch type @@ -245,12 +281,12 @@ extension JSON: Collection case .array: return .array(rawArray.startIndex) case .dictionary: - return .dictionary(dictionaryValue.startIndex) + return .dictionary(rawDictionary.startIndex) default: return .null } } - + public var endIndex: Index { switch type @@ -258,12 +294,12 @@ extension JSON: Collection case .array: return .array(rawArray.endIndex) case .dictionary: - return .dictionary(dictionaryValue.endIndex) + return .dictionary(rawDictionary.endIndex) default: return .null } } - + public func index(after i: Index) -> Index { switch i @@ -271,13 +307,13 @@ extension JSON: Collection case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): - return .dictionary(dictionaryValue.index(after: idx)) + return .dictionary(rawDictionary.index(after: idx)) default: return .null } - + } - + public subscript (position: Index) -> (String, JSON) { switch position @@ -285,13 +321,14 @@ extension JSON: Collection case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): - return dictionaryValue[idx] + let (key, value) = self.rawDictionary[idx] + return (key, JSON(value)) default: return ("", JSON.null) } } - - + + } // MARK: - Subscript @@ -322,7 +359,7 @@ extension String: JSONSubscriptType { } extension JSON { - + /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { @@ -346,7 +383,7 @@ extension JSON { } } } - + /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. fileprivate subscript(key key: String) -> JSON { get { @@ -368,7 +405,7 @@ extension JSON { } } } - + /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { get { @@ -384,18 +421,18 @@ extension JSON { } } } - + /** Find a json in the complex data structures by using array of Int and/or String as path. - + - parameter path: The target json's path. Example: - + let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] - + The same as: let name = json[9]["list"]["person"]["name"] - + - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { @@ -416,16 +453,16 @@ extension JSON { } } } - + /** Find a json in the complex data structures by using array of Int and/or String as path. - + - parameter path: The target json's path. Example: - + let name = json[9,"list","person","name"] - + The same as: let name = json[9]["list"]["person"]["name"] - + - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { @@ -441,36 +478,36 @@ extension JSON { // MARK: - LiteralConvertible extension JSON: Swift.ExpressibleByStringLiteral { - + public init(stringLiteral value: StringLiteralType) { self.init(value as Any) } - + public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as Any) } - + public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByIntegerLiteral { - + public init(integerLiteral value: IntegerLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByBooleanLiteral { - + public init(booleanLiteral value: BooleanLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByFloatLiteral { - + public init(floatLiteral value: FloatLiteralType) { self.init(value as Any) } @@ -481,7 +518,7 @@ extension JSON: Swift.ExpressibleByDictionaryLiteral { let array = elements self.init(dictionaryLiteral: array) } - + public init(dictionaryLiteral elements: [(String, Any)]) { let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in @@ -492,9 +529,9 @@ extension JSON: Swift.ExpressibleByDictionaryLiteral { } return JSON(dictionaryLiteral: initializeElement) } - + var dict = [String : Any](minimumCapacity: elements.count) - + for element in elements { let elementToSet: Any if let json = element.1 as? JSON { @@ -511,13 +548,13 @@ extension JSON: Swift.ExpressibleByDictionaryLiteral { } dict[element.0] = elementToSet } - + self.init(dict) } } extension JSON: Swift.ExpressibleByArrayLiteral { - + public init(arrayLiteral elements: Any...) { self.init(elements as Any) } @@ -534,7 +571,7 @@ extension JSON: Swift.ExpressibleByNilLiteral { // MARK: - Raw extension JSON: Swift.RawRepresentable { - + public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil @@ -542,19 +579,19 @@ extension JSON: Swift.RawRepresentable { self.init(rawValue) } } - + public var rawValue: Any { return self.object } - + public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } - + return try JSONSerialization.data(withJSONObject: self.object, options: opt) } - + public func rawString(_ encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { switch self.type { case .array, .dictionary: @@ -581,7 +618,7 @@ extension JSON: Swift.RawRepresentable { // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { - + public var description: String { if let string = self.rawString(options:.prettyPrinted) { return string @@ -589,7 +626,7 @@ extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertibl return "unknown" } } - + public var debugDescription: String { return description } @@ -598,7 +635,7 @@ extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertibl // MARK: - Array extension JSON { - + //Optional [JSON] public var array: [JSON]? { get { @@ -609,14 +646,14 @@ extension JSON { } } } - + //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } - + //Optional [AnyObject] public var arrayObject: [Any]? { get { @@ -640,7 +677,7 @@ extension JSON { // MARK: - Dictionary extension JSON { - + //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { @@ -653,12 +690,12 @@ extension JSON { return nil } } - + //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } - + //Optional [String : AnyObject] public var dictionaryObject: [String : Any]? { get { @@ -682,7 +719,7 @@ extension JSON { // MARK: - Bool extension JSON { // : Swift.Bool - + //Optional bool public var bool: Bool? { get { @@ -701,7 +738,7 @@ extension JSON { // : Swift.Bool } } } - + //Non-optional bool public var boolValue: Bool { get { @@ -727,7 +764,7 @@ extension JSON { // : Swift.Bool // MARK: - String extension JSON { - + //Optional string public var string: String? { get { @@ -746,7 +783,7 @@ extension JSON { } } } - + //Non-optional string public var stringValue: String { get { @@ -769,7 +806,7 @@ extension JSON { // MARK: - Number extension JSON { - + //Optional number public var number: NSNumber? { get { @@ -786,7 +823,7 @@ extension JSON { self.object = newValue ?? NSNull() } } - + //Non-optional number public var numberValue: NSNumber { get { @@ -813,7 +850,7 @@ extension JSON { //MARK: - Null extension JSON { - + public var null: NSNull? { get { switch self.type { @@ -839,7 +876,7 @@ extension JSON { //MARK: - URL extension JSON { - + //Optional URL public var URL: URL? { get { @@ -864,7 +901,7 @@ extension JSON { // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { - + public var double: Double? { get { return self.number?.doubleValue @@ -877,7 +914,7 @@ extension JSON { } } } - + public var doubleValue: Double { get { return self.numberValue.doubleValue @@ -886,7 +923,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var float: Float? { get { return self.number?.floatValue @@ -899,7 +936,7 @@ extension JSON { } } } - + public var floatValue: Float { get { return self.numberValue.floatValue @@ -908,7 +945,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int: Int? { get @@ -926,7 +963,7 @@ extension JSON { } } } - + public var intValue: Int { get { return self.numberValue.intValue @@ -935,7 +972,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt: UInt? { get { return self.number?.uintValue @@ -948,7 +985,7 @@ extension JSON { } } } - + public var uIntValue: UInt { get { return self.numberValue.uintValue @@ -957,7 +994,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int8: Int8? { get { return self.number?.int8Value @@ -970,7 +1007,7 @@ extension JSON { } } } - + public var int8Value: Int8 { get { return self.numberValue.int8Value @@ -979,7 +1016,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt8: UInt8? { get { return self.number?.uint8Value @@ -992,7 +1029,7 @@ extension JSON { } } } - + public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value @@ -1001,7 +1038,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int16: Int16? { get { return self.number?.int16Value @@ -1014,7 +1051,7 @@ extension JSON { } } } - + public var int16Value: Int16 { get { return self.numberValue.int16Value @@ -1023,7 +1060,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt16: UInt16? { get { return self.number?.uint16Value @@ -1036,7 +1073,7 @@ extension JSON { } } } - + public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value @@ -1045,7 +1082,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int32: Int32? { get { return self.number?.int32Value @@ -1058,7 +1095,7 @@ extension JSON { } } } - + public var int32Value: Int32 { get { return self.numberValue.int32Value @@ -1067,7 +1104,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt32: UInt32? { get { return self.number?.uint32Value @@ -1080,7 +1117,7 @@ extension JSON { } } } - + public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value @@ -1089,7 +1126,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var int64: Int64? { get { return self.number?.int64Value @@ -1102,7 +1139,7 @@ extension JSON { } } } - + public var int64Value: Int64 { get { return self.numberValue.int64Value @@ -1111,7 +1148,7 @@ extension JSON { self.object = NSNumber(value: newValue) } } - + public var uInt64: UInt64? { get { return self.number?.uint64Value @@ -1124,7 +1161,7 @@ extension JSON { } } } - + public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value @@ -1139,7 +1176,7 @@ extension JSON { extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber @@ -1159,7 +1196,7 @@ public func ==(lhs: JSON, rhs: JSON) -> Bool { } public func <=(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber @@ -1179,7 +1216,7 @@ public func <=(lhs: JSON, rhs: JSON) -> Bool { } public func >=(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber @@ -1199,7 +1236,7 @@ public func >=(lhs: JSON, rhs: JSON) -> Bool { } public func >(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber @@ -1211,7 +1248,7 @@ public func >(lhs: JSON, rhs: JSON) -> Bool { } public func <(lhs: JSON, rhs: JSON) -> Bool { - + switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber @@ -1258,7 +1295,7 @@ func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { - + switch (lhs.isBool, rhs.isBool) { case (false, true): return false @@ -1270,7 +1307,7 @@ func <(lhs: NSNumber, rhs: NSNumber) -> Bool { } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { - + switch (lhs.isBool, rhs.isBool) { case (false, true): return false @@ -1282,7 +1319,7 @@ func >(lhs: NSNumber, rhs: NSNumber) -> Bool { } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { - + switch (lhs.isBool, rhs.isBool) { case (false, true): return false @@ -1294,7 +1331,7 @@ func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { - + switch (lhs.isBool, rhs.isBool) { case (false, true): return false From e64f17ffdbc3a11bafbb200b6d5e07933d7c603e Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Wed, 16 Nov 2016 23:07:25 +0800 Subject: [PATCH 096/260] Add performance test --- Tests/SwiftyJSONTests/SequenceTypeTests.swift | 60 +++++++++++-------- 1 file changed, 36 insertions(+), 24 deletions(-) diff --git a/Tests/SwiftyJSONTests/SequenceTypeTests.swift b/Tests/SwiftyJSONTests/SequenceTypeTests.swift index a9ff6cf6..62bd7dcf 100644 --- a/Tests/SwiftyJSONTests/SequenceTypeTests.swift +++ b/Tests/SwiftyJSONTests/SequenceTypeTests.swift @@ -46,7 +46,7 @@ class SequenceTypeTests: XCTestCase { XCTFail("Can't find the test JSON file") } } - + func testArrayAllNumber() { var json:JSON = [1,2.0,3.3,123456789,987654321.123456789] XCTAssertEqual(json.count, 5) @@ -62,11 +62,11 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual(index, 5) XCTAssertEqual(array, [1,2.0,3.3,123456789,987654321.123456789]) } - + func testArrayAllBool() { var json:JSON = JSON([true, false, false, true, true]) XCTAssertEqual(json.count, 5) - + var index = 0 var array = [Bool]() for (i, sub) in json { @@ -78,11 +78,11 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual(index, 5) XCTAssertEqual(array, [true, false, false, true, true]) } - + func testArrayAllString() { var json:JSON = JSON(rawValue: ["aoo","bpp","zoo"] as NSArray)! XCTAssertEqual(json.count, 3) - + var index = 0 var array = [String]() for (i, sub) in json { @@ -94,11 +94,11 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual(index, 3) XCTAssertEqual(array, ["aoo","bpp","zoo"]) } - + func testArrayWithNull() { var json:JSON = JSON(rawValue: ["aoo","bpp", NSNull() ,"zoo"] as NSArray)! XCTAssertEqual(json.count, 4) - + var index = 0 var array = [AnyObject]() for (i, sub) in json { @@ -111,11 +111,11 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual(array[0] as? String, "aoo") XCTAssertEqual(array[2] as? NSNull, NSNull()) } - + func testArrayAllDictionary() { var json:JSON = [["1":1, "2":2], ["a":"A", "b":"B"], ["null":NSNull()]] XCTAssertEqual(json.count, 3) - + var index = 0 var array = [AnyObject]() for (i, sub) in json { @@ -131,11 +131,11 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual((array[1] as! [String : String])["b"]!, "B") XCTAssertEqual((array[2] as! [String : NSNull])["null"]!, NSNull()) } - + func testDictionaryAllNumber() { var json:JSON = ["double":1.11111, "int":987654321] XCTAssertEqual(json.count, 2) - + var index = 0 var dictionary = [String:NSNumber]() for (key, sub) in json { @@ -143,16 +143,16 @@ class SequenceTypeTests: XCTestCase { dictionary[key] = sub.number! index += 1 } - + XCTAssertEqual(index, 2) XCTAssertEqual(dictionary["double"]! as NSNumber, 1.11111) XCTAssertEqual(dictionary["int"]! as NSNumber, 987654321) } - + func testDictionaryAllBool() { var json:JSON = ["t":true, "f":false, "false":false, "tr":true, "true":true] XCTAssertEqual(json.count, 5) - + var index = 0 var dictionary = [String:Bool]() for (key, sub) in json { @@ -160,16 +160,16 @@ class SequenceTypeTests: XCTestCase { dictionary[key] = sub.bool! index += 1 } - + XCTAssertEqual(index, 5) XCTAssertEqual(dictionary["t"]! as Bool, true) XCTAssertEqual(dictionary["false"]! as Bool, false) } - + func testDictionaryAllString() { var json:JSON = JSON(rawValue: ["a":"aoo","bb":"bpp","z":"zoo"] as NSDictionary)! XCTAssertEqual(json.count, 3) - + var index = 0 var dictionary = [String:String]() for (key, sub) in json { @@ -177,16 +177,16 @@ class SequenceTypeTests: XCTestCase { dictionary[key] = sub.string! index += 1 } - + XCTAssertEqual(index, 3) XCTAssertEqual(dictionary["a"]! as String, "aoo") XCTAssertEqual(dictionary["bb"]! as String, "bpp") } - + func testDictionaryWithNull() { var json:JSON = JSON(rawValue: ["a":"aoo","bb":"bpp","null":NSNull(), "z":"zoo"] as NSDictionary)! XCTAssertEqual(json.count, 4) - + var index = 0 var dictionary = [String:AnyObject]() for (key, sub) in json { @@ -194,18 +194,18 @@ class SequenceTypeTests: XCTestCase { dictionary[key] = sub.object as AnyObject? index += 1 } - + XCTAssertEqual(index, 4) XCTAssertEqual(dictionary["a"]! as? String, "aoo") XCTAssertEqual(dictionary["bb"]! as? String, "bpp") XCTAssertEqual(dictionary["null"]! as? NSNull, NSNull()) } - + func testDictionaryAllArray() { var json:JSON = JSON (["Number":[NSNumber(value:1),NSNumber(value:2.123456),NSNumber(value:123456789)], "String":["aa","bbb","cccc"], "Mix":[true, "766", NSNull(), 655231.9823]]) XCTAssertEqual(json.count, 3) - + var index = 0 var dictionary = [String:AnyObject]() for (key, sub) in json { @@ -213,7 +213,7 @@ class SequenceTypeTests: XCTestCase { dictionary[key] = sub.object as AnyObject? index += 1 } - + XCTAssertEqual(index, 3) XCTAssertEqual((dictionary["Number"] as! NSArray)[0] as? Int, 1) XCTAssertEqual((dictionary["Number"] as! NSArray)[1] as? Double, 2.123456) @@ -223,4 +223,16 @@ class SequenceTypeTests: XCTestCase { XCTAssertEqual((dictionary["Mix"] as! NSArray)[2] as? NSNull, NSNull()) XCTAssertEqual((dictionary["Mix"] as! NSArray)[3] as? Double, 655231.9823) } + + func testDictionaryIteratingPerformance() { + var json: JSON = [:] + for i in 1...1000 { + json[String(i)] = "hello" + } + measure { + for (key, value) in json { + print(key, value) + } + } + } } From 885c387169ed3f62032158a6f5235884d436a1f9 Mon Sep 17 00:00:00 2001 From: Zhigang Fang Date: Wed, 16 Nov 2016 23:22:21 +0800 Subject: [PATCH 097/260] Update version in pod spec --- SwiftyJSON.podspec | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 1a29fe55..111a6976 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "3.1.1" + s.version = "3.1.3" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } @@ -11,7 +11,7 @@ Pod::Spec.new do |s| s.ios.deployment_target = "8.0" s.watchos.deployment_target = "2.0" s.tvos.deployment_target = "9.0" - s.source = { :git => "https://github.com/SwiftyJSON/SwiftyJSON.git", :tag => "v#{s.version}" } + s.source = { :git => "https://github.com/SwiftyJSON/SwiftyJSON.git", :tag => s.version } s.source_files = "Source/*.swift" s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3.0', From c911942dd1ccd710d8ae106ca51654864bed1d16 Mon Sep 17 00:00:00 2001 From: Simon Tsai Date: Wed, 16 Nov 2016 11:23:13 -0500 Subject: [PATCH 098/260] Instead of checking for the Int8 type explicitly when setting 'object', cast the Int8 value to an Int and pass that into an NSNumber when setting 'int8' or 'int8Value' --- Source/SwiftyJSON.swift | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 4aa6fcc7..c9de1969 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -157,9 +157,6 @@ public struct JSON { set { _error = nil switch newValue { - case let int8Value as Int8 where type(of: newValue) == Int8.self: - _type = .number - self.rawNumber = NSNumber(value: Int(int8Value)) case let number as NSNumber: if number.isBool { _type = .bool @@ -967,7 +964,7 @@ extension JSON { } set { if let newValue = newValue { - self.object = newValue + self.object = NSNumber(value: Int(newValue)) } else { self.object = NSNull() } @@ -979,7 +976,7 @@ extension JSON { return self.numberValue.int8Value } set { - self.object = newValue + self.object = NSNumber(value: Int(newValue)) } } From 9a79305facf4a0966022b5431b242609e65af6b0 Mon Sep 17 00:00:00 2001 From: Guillaume Sabran Date: Mon, 26 Sep 2016 09:19:18 -0700 Subject: [PATCH 099/260] represent strings with nil as if it was nsnull --- Source/SwiftyJSON.swift | 71 ++++++++++++++++++++-- Tests/SwiftyJSONTests/PrintableTests.swift | 42 +++++++++++++ 2 files changed, 107 insertions(+), 6 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 43483c11..ab0c676f 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -171,8 +171,9 @@ public struct JSON { case _ as NSNull: _type = .null case let array as [JSON]: - _type = .array - self.rawArray = array.map { $0.object } + _type = .array + case nil: + _type = .null case let array as [Any]: _type = .array self.rawArray = array @@ -591,13 +592,71 @@ extension JSON: Swift.RawRepresentable { return try JSONSerialization.data(withJSONObject: self.object, options: opt) } + + public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted, maxDepth: Int = 10) -> String? { + do { + return try _rawString(encoding, options: opt, maxDepth: maxDepth) + } catch { + print("Could not serialize object to JSON because:", error.localizedDescription) + return nil + } + } - public func rawString(_ encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { + private func _rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted, maxDepth: Int = 10) throws -> String? { + if (maxDepth < 0) { + throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxDepth and make sure there is no reference loop"]) + } switch self.type { - case .array, .dictionary: + case .dictionary: + do { + guard let dict = self.object as? [String: Any?] else { + return nil + } + let body = try dict.keys.map { key throws -> String in + guard let value = dict[key] else { + return "\"\(key)\": null" + } + guard value != nil else { + return "\"\(key)\": null" + } + + let nestedValue = JSON(value) + guard let nestedString = try nestedValue._rawString(encoding, options: opt, maxDepth: maxDepth - 1) else { + throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) + } + if nestedValue.type == .string { + return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" + } else { + return "\"\(key)\": \(nestedString)" + } + } + + return "{\(body.joined(separator: ","))}" + } catch _ { + return nil + } + case .array: do { - let data = try self.rawData(options: opt) - return String(data: data, encoding: encoding) + guard let array = self.object as? [Any?] else { + return nil + } + let body = try array.map { value throws -> String in + guard value != nil else { + return "null" + } + + let nestedValue = JSON(value) + guard let nestedString = try nestedValue._rawString(encoding, options: opt, maxDepth: maxDepth - 1) else { + throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) + } + if nestedValue.type == .string { + return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" + } else { + return nestedString + } + } + + return "[\(body.joined(separator: ","))]" } catch _ { return nil } diff --git a/Tests/SwiftyJSONTests/PrintableTests.swift b/Tests/SwiftyJSONTests/PrintableTests.swift index 5672c13a..849b6581 100644 --- a/Tests/SwiftyJSONTests/PrintableTests.swift +++ b/Tests/SwiftyJSONTests/PrintableTests.swift @@ -62,6 +62,26 @@ class PrintableTests: XCTestCase { XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0) } + + func testArrayWithStrings() { + let array = ["\"123\""] + let json = JSON(array) + var description = json.description.replacingOccurrences(of: "\n", with: "") + description = description.replacingOccurrences(of: " ", with: "") + XCTAssertEqual(description, "[\"\\\"123\\\"\"]") + XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) + XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0) + } + + func testArrayWithOptionals() { + let array = [1,2,"4",5,"6",nil] as [Any?] + let json = JSON(array) + var description = json.description.replacingOccurrences(of: "\n", with: "") + description = description.replacingOccurrences(of: " ", with: "") + XCTAssertEqual(description, "[1,2,\"4\",5,\"6\",null]") + XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) + XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0) + } func testDictionary() { let json:JSON = ["1":2,"2":"two", "3":3] @@ -72,4 +92,26 @@ class PrintableTests: XCTestCase { XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: String.CompareOptions.caseInsensitive) != nil) XCTAssertTrue(debugDescription.range(of: "\"3\":3", options: String.CompareOptions.caseInsensitive) != nil) } + + func testDictionaryWithStrings() { + let dict = ["foo":"{\"bar\":123}"] as [String : Any] + let json = JSON(dict) + var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") + debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") + XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) + let exceptedResult = "{\"foo\":\"{\\\"bar\\\":123}\"}" + XCTAssertEqual(debugDescription, exceptedResult) + } + + func testDictionaryWithOptionals() { + let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] + let json = JSON(dict) + var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") + debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") + print("debugDescription", debugDescription) + XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) + XCTAssertTrue(debugDescription.range(of: "\"1\":2", options: NSString.CompareOptions.caseInsensitive) != nil) + XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: NSString.CompareOptions.caseInsensitive) != nil) + XCTAssertTrue(debugDescription.range(of: "\"3\":null", options: NSString.CompareOptions.caseInsensitive) != nil) + } } From 62b490c5f972198480cd0c5bcdc6ad9a27841320 Mon Sep 17 00:00:00 2001 From: Guillaume Sabran Date: Mon, 26 Sep 2016 10:00:23 -0700 Subject: [PATCH 100/260] make casting nil to nsnull optional --- Source/SwiftyJSON.swift | 120 +++++++++++++-------- Tests/SwiftyJSONTests/PrintableTests.swift | 21 ++-- 2 files changed, 91 insertions(+), 50 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index ab0c676f..58d0617b 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -591,52 +591,79 @@ extension JSON: Swift.RawRepresentable { } return try JSONSerialization.data(withJSONObject: self.object, options: opt) - } - - public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted, maxDepth: Int = 10) -> String? { - do { - return try _rawString(encoding, options: opt, maxDepth: maxDepth) - } catch { - print("Could not serialize object to JSON because:", error.localizedDescription) - return nil - } - } - - private func _rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted, maxDepth: Int = 10) throws -> String? { - if (maxDepth < 0) { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxDepth and make sure there is no reference loop"]) + } + + public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { + do { + return try _rawString(encoding, options: [.jsonSerialization: opt]) + } catch { + print("Could not serialize object to JSON because:", error.localizedDescription) + return nil + } + } + + public func rawString(options: [writtingOptionsKeys: Any]) -> String? { + let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 + let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 + do { + return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) + } catch { + print("Could not serialize object to JSON because:", error.localizedDescription) + return nil + } + } + + private func _rawString( + _ encoding: String.Encoding = .utf8, + options: [writtingOptionsKeys: Any], + maxObjectDepth: Int = 10 + ) throws -> String? { + if (maxObjectDepth < 0) { + throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop"]) } switch self.type { - case .dictionary: + case .dictionary: + do { + if !(options[.castNilToNSNull] as? Bool ?? false) { + let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted + let data = try self.rawData(options: jsonOption) + return String(data: data, encoding: encoding) + } + + guard let dict = self.object as? [String: Any?] else { + return nil + } + let body = try dict.keys.map { key throws -> String in + guard let value = dict[key] else { + return "\"\(key)\": null" + } + guard value != nil else { + return "\"\(key)\": null" + } + + let nestedValue = JSON(value) + guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { + throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) + } + if nestedValue.type == .string { + return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" + } else { + return "\"\(key)\": \(nestedString)" + } + } + + return "{\(body.joined(separator: ","))}" + } catch _ { + return nil + } + case .array: do { - guard let dict = self.object as? [String: Any?] else { - return nil - } - let body = try dict.keys.map { key throws -> String in - guard let value = dict[key] else { - return "\"\(key)\": null" - } - guard value != nil else { - return "\"\(key)\": null" - } + if !(options[.castNilToNSNull] as? Bool ?? false) { + let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted + let data = try self.rawData(options: jsonOption) + return String(data: data, encoding: encoding) + } - let nestedValue = JSON(value) - guard let nestedString = try nestedValue._rawString(encoding, options: opt, maxDepth: maxDepth - 1) else { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) - } - if nestedValue.type == .string { - return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" - } else { - return "\"\(key)\": \(nestedString)" - } - } - - return "{\(body.joined(separator: ","))}" - } catch _ { - return nil - } - case .array: - do { guard let array = self.object as? [Any?] else { return nil } @@ -646,7 +673,7 @@ extension JSON: Swift.RawRepresentable { } let nestedValue = JSON(value) - guard let nestedString = try nestedValue._rawString(encoding, options: opt, maxDepth: maxDepth - 1) else { + guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } if nestedValue.type == .string { @@ -1404,3 +1431,10 @@ func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { return lhs.compare(rhs) != .orderedAscending } } + +public enum writtingOptionsKeys { + case jsonSerialization + case castNilToNSNull + case maxObjextDepth + case encoding +} diff --git a/Tests/SwiftyJSONTests/PrintableTests.swift b/Tests/SwiftyJSONTests/PrintableTests.swift index 849b6581..d8361685 100644 --- a/Tests/SwiftyJSONTests/PrintableTests.swift +++ b/Tests/SwiftyJSONTests/PrintableTests.swift @@ -76,7 +76,11 @@ class PrintableTests: XCTestCase { func testArrayWithOptionals() { let array = [1,2,"4",5,"6",nil] as [Any?] let json = JSON(array) - var description = json.description.replacingOccurrences(of: "\n", with: "") + guard var description = json.rawString(options: [.castNilToNSNull: true]) else { + XCTFail("could not represent array") + return + } + description = description.replacingOccurrences(of: "\n", with: "") description = description.replacingOccurrences(of: " ", with: "") XCTAssertEqual(description, "[1,2,\"4\",5,\"6\",null]") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) @@ -106,12 +110,15 @@ class PrintableTests: XCTestCase { func testDictionaryWithOptionals() { let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] let json = JSON(dict) - var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") - debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") - print("debugDescription", debugDescription) + guard var description = json.rawString(options: [.castNilToNSNull: true]) else { + XCTFail("could not represent dictionary") + return + } + description = description.replacingOccurrences(of: "\n", with: "") + description = description.replacingOccurrences(of: " ", with: "") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) - XCTAssertTrue(debugDescription.range(of: "\"1\":2", options: NSString.CompareOptions.caseInsensitive) != nil) - XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: NSString.CompareOptions.caseInsensitive) != nil) - XCTAssertTrue(debugDescription.range(of: "\"3\":null", options: NSString.CompareOptions.caseInsensitive) != nil) + XCTAssertTrue(description.range(of: "\"1\":2", options: NSString.CompareOptions.caseInsensitive) != nil) + XCTAssertTrue(description.range(of: "\"2\":\"two\"", options: NSString.CompareOptions.caseInsensitive) != nil) + XCTAssertTrue(description.range(of: "\"3\":null", options: NSString.CompareOptions.caseInsensitive) != nil) } } From 5c18ba9df5307ebacfbf9046562a1ac2fd376bc9 Mon Sep 17 00:00:00 2001 From: Guillaume Sabran Date: Wed, 16 Nov 2016 14:40:21 -0800 Subject: [PATCH 101/260] update readme --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index 0f29db0b..f1c1ab62 100644 --- a/README.md +++ b/README.md @@ -442,6 +442,17 @@ let auth: JSON = [ ] ``` +## String representation +There are two options available: +- use the default Swift one +- use a custom one that will handle optionals well and represent `nil` as `"null"`: +```swift +let data = ["1":2, "2":"two", "3": nil] as [String: Any?] +let json = JSON(dict) +let representation = json.rawString(options: [.castNilToNSNull: true]) +// representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} +``` + ## Work with Alamofire SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: From 588db575856bfb1625d22cec5c16f15008327df9 Mon Sep 17 00:00:00 2001 From: Daniel Kiedrowski Date: Thu, 17 Nov 2016 16:34:02 +0100 Subject: [PATCH 102/260] Added a function to deep merge a JSON object into another JSON object destructively and non-destructively. --- Source/SwiftyJSON.swift | 36 +++++++++++ SwiftyJSON.xcodeproj/project.pbxproj | 8 +++ Tests/SwiftyJSONTests/MergeTests.swift | 84 ++++++++++++++++++++++++++ 3 files changed, 128 insertions(+) create mode 100644 Tests/SwiftyJSONTests/MergeTests.swift diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 58d0617b..3e533bb2 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -123,6 +123,42 @@ public struct JSON { } self.init(dictionary) } + + /** + Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. + + - parameter other: The JSON which gets merged into this JSON + */ + public mutating func merge(_ other: JSON) { + if self.type == other.type { + switch self.type { + case .dictionary: + for (key, _) in other { + self[key].merge(other[key]) + } + case .array: + self = JSON(self.arrayValue + other.arrayValue) + default: + self = other + } + } else { + self = other + } + } + + /** + Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. + + - parameter other: The JSON which gets merged into this JSON + - returns: New merged JSON + */ + public func merged(other: JSON) -> JSON { + var merged = self + merged.merge(other) + return merged + } /// Private object fileprivate var rawArray: [Any] = [] diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 4bddfa14..c4e6df5e 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -7,6 +7,9 @@ objects = { /* Begin PBXBuildFile section */ + 1B587CC61DDE04770012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; + 1B587CC71DDE04780012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; + 1B587CC81DDE04790012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; 2E4FEFE119575BE100351305 /* SwiftyJSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E4FEFE019575BE100351305 /* SwiftyJSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2E4FEFE719575BE100351305 /* SwiftyJSON.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2E4FEFDB19575BE100351305 /* SwiftyJSON.framework */; }; 5DD502911D9B21810004C112 /* NestedJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD502901D9B21810004C112 /* NestedJSONTests.swift */; }; @@ -91,6 +94,7 @@ /* Begin PBXFileReference section */ 030B6CDC1A6E171D00C2D4F1 /* Info-OSX.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-OSX.plist"; sourceTree = ""; }; + 1B587CC41DDE04360012D8DB /* MergeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MergeTests.swift; sourceTree = ""; }; 2E4FEFDB19575BE100351305 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 2E4FEFDF19575BE100351305 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; 2E4FEFE019575BE100351305 /* SwiftyJSON.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SwiftyJSON.h; sourceTree = ""; }; @@ -226,6 +230,7 @@ 2E4FEFEA19575BE100351305 /* SwiftyJSONTests */ = { isa = PBXGroup; children = ( + 1B587CC41DDE04360012D8DB /* MergeTests.swift */, A885D1DA19CFCFF0002FD4C3 /* Tests.json */, A86BAA0D19EBC32B009EAAEB /* PerformanceTests.swift */, A885D1D119CF1EE6002FD4C3 /* BaseTests.swift */, @@ -550,6 +555,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 1B587CC61DDE04770012D8DB /* MergeTests.swift in Sources */, A87080E819E439DA00CDE086 /* NumberTests.swift in Sources */, A87080E419E3C2A600CDE086 /* SequenceTypeTests.swift in Sources */, 5DD502911D9B21810004C112 /* NestedJSONTests.swift in Sources */, @@ -587,6 +593,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 1B587CC71DDE04780012D8DB /* MergeTests.swift in Sources */, 9C459EFB1A9103C1008C9A41 /* SequenceTypeTests.swift in Sources */, 9C459F001A9103C1008C9A41 /* ComparableTests.swift in Sources */, 5DD502921D9B21810004C112 /* NestedJSONTests.swift in Sources */, @@ -608,6 +615,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 1B587CC81DDE04790012D8DB /* MergeTests.swift in Sources */, A8580F801BCF69A000DA927B /* PerformanceTests.swift in Sources */, A8580F811BCF69A000DA927B /* BaseTests.swift in Sources */, 5DD502931D9B21810004C112 /* NestedJSONTests.swift in Sources */, diff --git a/Tests/SwiftyJSONTests/MergeTests.swift b/Tests/SwiftyJSONTests/MergeTests.swift new file mode 100644 index 00000000..10564bf7 --- /dev/null +++ b/Tests/SwiftyJSONTests/MergeTests.swift @@ -0,0 +1,84 @@ +// +// JSONTests.swift +// +// Created by Daniel Kiedrowski on 17.11.16. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import XCTest +import SwiftyJSON + +class JSONTests: XCTestCase { + func testPrimitiveType() { + let A = JSON("a") + let B = JSON("b") + XCTAssertEqual(A.merged(other: B), B) + } + + func testMergeEqual() { + let json = JSON(["a": "A"]) + XCTAssertEqual(json.merged(other: json), json) + } + + func testMergeUnequalValues() { + let A = JSON(["a": "A"]) + let B = JSON(["a": "B"]) + XCTAssertEqual(A.merged(other: B), B) + } + + func testMergeUnequalKeysAndValues() { + let A = JSON(["a": "A"]) + let B = JSON(["b": "B"]) + XCTAssertEqual(A.merged(other: B), JSON(["a": "A", "b": "B"])) + } + + func testMergeFilledAndEmpty() { + let A = JSON(["a": "A"]) + let B = JSON([:]) + XCTAssertEqual(A.merged(other: B), A) + } + + func testMergeEmptyAndFilled() { + let A = JSON([:]) + let B = JSON(["a": "A"]) + XCTAssertEqual(A.merged(other: B), B) + } + + func testMergeArray() { + let A = JSON(["a"]) + let B = JSON(["b"]) + XCTAssertEqual(A.merged(other: B), JSON(["a", "b"])) + } + + func testMergeNestedJSONs() { + let A = JSON([ + "nested": [ + "A": "a" + ] + ]) + + let B = JSON([ + "nested": [ + "A": "b" + ] + ]) + + XCTAssertEqual(A.merged(other: B), B) + } +} From 6de5453a604597914d23b5a0cd4f9ea6581dc21c Mon Sep 17 00:00:00 2001 From: Fang-Pen Lin Date: Sun, 20 Nov 2016 22:27:25 -0800 Subject: [PATCH 103/260] Fix duplicate comma typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f1c1ab62..0d2798a6 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ It's not good. Even if we use optional chaining, it would be messy: ```swift -if let JSONObject = try JSONSerialization.jsonObject(with: data,, options: .allowFragments) as? [[String: Any]], +if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String { // There's our username } From 1eac774469ff84924dc998932b7b245656c15c7f Mon Sep 17 00:00:00 2001 From: Christopher Katzmann Date: Mon, 21 Nov 2016 15:25:31 -0600 Subject: [PATCH 104/260] update Integration section of README to reflect latest version in SPM usage subsection --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f1c1ab62..5d86f477 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ let package = Package( name: "YOUR_PROJECT_NAME", targets: [], dependencies: [ - .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1,0,0).. Date: Mon, 21 Nov 2016 20:10:06 -0800 Subject: [PATCH 105/260] Fix all compilation warnings --- Source/SwiftyJSON.swift | 10 +++++----- Tests/SwiftyJSONTests/NumberTests.swift | 4 +--- Tests/SwiftyJSONTests/RawTests.swift | 12 ++++-------- Tests/SwiftyJSONTests/StringTests.swift | 8 +++++--- 4 files changed, 15 insertions(+), 19 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 58d0617b..f74e21b5 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -170,7 +170,7 @@ public struct JSON { self.rawString = string case _ as NSNull: _type = .null - case let array as [JSON]: + case _ as [JSON]: _type = .array case nil: _type = .null @@ -637,11 +637,11 @@ extension JSON: Swift.RawRepresentable { guard let value = dict[key] else { return "\"\(key)\": null" } - guard value != nil else { + guard let unwrappedValue = value else { return "\"\(key)\": null" } - let nestedValue = JSON(value) + let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } @@ -668,11 +668,11 @@ extension JSON: Swift.RawRepresentable { return nil } let body = try array.map { value throws -> String in - guard value != nil else { + guard let unwrappedValue = value else { return "null" } - let nestedValue = JSON(value) + let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } diff --git a/Tests/SwiftyJSONTests/NumberTests.swift b/Tests/SwiftyJSONTests/NumberTests.swift index 37e89cc8..828bae68 100644 --- a/Tests/SwiftyJSONTests/NumberTests.swift +++ b/Tests/SwiftyJSONTests/NumberTests.swift @@ -189,7 +189,6 @@ class NumberTests: XCTestCase { json.int8Value = n0.int8Value XCTAssertTrue(json.int8! == n0.int8Value) XCTAssertTrue(json.int8Value == n0.int8Value) - print(json.number) XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") @@ -260,8 +259,7 @@ class NumberTests: XCTestCase { json.int16Value = n0.int16Value XCTAssertTrue(json.int16! == n0.int16Value) XCTAssertTrue(json.int16Value == n0.int16Value) - print(json.number) - XCTAssertTrue(json.number! == n0) + XCTAssertEqual(json.number, n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") diff --git a/Tests/SwiftyJSONTests/RawTests.swift b/Tests/SwiftyJSONTests/RawTests.swift index a31b84ef..d45f1cec 100644 --- a/Tests/SwiftyJSONTests/RawTests.swift +++ b/Tests/SwiftyJSONTests/RawTests.swift @@ -75,25 +75,21 @@ class RawTests: XCTestCase { func testString() { let json:JSON = "I'm a json" - print(json.rawString()) - XCTAssertTrue(json.rawString() == "I'm a json") + XCTAssertEqual(json.rawString(), "I'm a json") } func testNumber() { let json:JSON = 123456789.123 - print(json.rawString()) - XCTAssertTrue(json.rawString() == "123456789.123") + XCTAssertEqual(json.rawString(), "123456789.123") } func testBool() { let json:JSON = true - print(json.rawString()) - XCTAssertTrue(json.rawString() == "true") + XCTAssertEqual(json.rawString(), "true") } func testNull() { let json:JSON = JSON.null - print(json.rawString()) - XCTAssertTrue(json.rawString() == "null") + XCTAssertEqual(json.rawString(), "null") } } diff --git a/Tests/SwiftyJSONTests/StringTests.swift b/Tests/SwiftyJSONTests/StringTests.swift index 7fcd48c6..9ba2b1df 100644 --- a/Tests/SwiftyJSONTests/StringTests.swift +++ b/Tests/SwiftyJSONTests/StringTests.swift @@ -59,10 +59,12 @@ class StringTests: XCTestCase { func testURLPercentEscapes() { let emDash = "\\u2014" let urlString = "http://examble.com/unencoded" + emDash + "string" - let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) + guard let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { + return XCTFail("Couldn't encode URL string \(urlString)") + } let json = JSON(urlString) - XCTAssertEqual(json.URL!, URL(string: encodedURLString!)!, "Wrong unpacked ") + XCTAssertEqual(json.URL!, URL(string: encodedURLString)!, "Wrong unpacked ") let preEscaped = JSON(encodedURLString) - XCTAssertEqual(preEscaped.URL!, URL(string: encodedURLString!)!, "Wrong unpacked ") + XCTAssertEqual(preEscaped.URL!, URL(string: encodedURLString)!, "Wrong unpacked ") } } From d5552cb78fa3182042f06b2792022d4b5e7cb861 Mon Sep 17 00:00:00 2001 From: Daniel Kiedrowski Date: Tue, 22 Nov 2016 10:31:22 +0100 Subject: [PATCH 106/260] Added label with: to merge and merged. --- Source/SwiftyJSON.swift | 8 ++++---- Tests/SwiftyJSONTests/MergeTests.swift | 16 ++++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 3e533bb2..fe75812b 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -130,12 +130,12 @@ public struct JSON { - parameter other: The JSON which gets merged into this JSON */ - public mutating func merge(_ other: JSON) { + public mutating func merge(with other: JSON) { if self.type == other.type { switch self.type { case .dictionary: for (key, _) in other { - self[key].merge(other[key]) + self[key].merge(with: other[key]) } case .array: self = JSON(self.arrayValue + other.arrayValue) @@ -154,9 +154,9 @@ public struct JSON { - parameter other: The JSON which gets merged into this JSON - returns: New merged JSON */ - public func merged(other: JSON) -> JSON { + public func merged(with other: JSON) -> JSON { var merged = self - merged.merge(other) + merged.merge(with: other) return merged } diff --git a/Tests/SwiftyJSONTests/MergeTests.swift b/Tests/SwiftyJSONTests/MergeTests.swift index 10564bf7..30aec15b 100644 --- a/Tests/SwiftyJSONTests/MergeTests.swift +++ b/Tests/SwiftyJSONTests/MergeTests.swift @@ -28,42 +28,42 @@ class JSONTests: XCTestCase { func testPrimitiveType() { let A = JSON("a") let B = JSON("b") - XCTAssertEqual(A.merged(other: B), B) + XCTAssertEqual(A.merged(with: B), B) } func testMergeEqual() { let json = JSON(["a": "A"]) - XCTAssertEqual(json.merged(other: json), json) + XCTAssertEqual(json.merged(with: json), json) } func testMergeUnequalValues() { let A = JSON(["a": "A"]) let B = JSON(["a": "B"]) - XCTAssertEqual(A.merged(other: B), B) + XCTAssertEqual(A.merged(with: B), B) } func testMergeUnequalKeysAndValues() { let A = JSON(["a": "A"]) let B = JSON(["b": "B"]) - XCTAssertEqual(A.merged(other: B), JSON(["a": "A", "b": "B"])) + XCTAssertEqual(A.merged(with: B), JSON(["a": "A", "b": "B"])) } func testMergeFilledAndEmpty() { let A = JSON(["a": "A"]) let B = JSON([:]) - XCTAssertEqual(A.merged(other: B), A) + XCTAssertEqual(A.merged(with: B), A) } func testMergeEmptyAndFilled() { let A = JSON([:]) let B = JSON(["a": "A"]) - XCTAssertEqual(A.merged(other: B), B) + XCTAssertEqual(A.merged(with: B), B) } func testMergeArray() { let A = JSON(["a"]) let B = JSON(["b"]) - XCTAssertEqual(A.merged(other: B), JSON(["a", "b"])) + XCTAssertEqual(A.merged(with: B), JSON(["a", "b"])) } func testMergeNestedJSONs() { @@ -79,6 +79,6 @@ class JSONTests: XCTestCase { ] ]) - XCTAssertEqual(A.merged(other: B), B) + XCTAssertEqual(A.merged(with: B), B) } } From c28f3f537ae5d1a01bf618b4a8fe297e7d658875 Mon Sep 17 00:00:00 2001 From: Daniel Kiedrowski Date: Tue, 22 Nov 2016 10:51:32 +0100 Subject: [PATCH 107/260] Added documentation for merging two JSONs. --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/README.md b/README.md index f1c1ab62..a7dac962 100644 --- a/README.md +++ b/README.md @@ -442,6 +442,54 @@ let auth: JSON = [ ] ``` +#### Merging + +It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the `other` JSON. + +If both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment: + +- In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. +- In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. + +In case, where two fields in a JSON have a different types, the value will get always overwritten. + +There are two different fashions for merging: `merge`modifies the original JSON, whereas `merged` works non-destructively on a copy. + +```swift +let original: JSON = [ + "first_name": "John", + "age": 20, + "skills": ["Coding", "Reading"], + "address": [ + "street": "Front St", + "zip": "12345", + ] +] + +let update: JSON = [ + "last_name": "Doe", + "age": 21, + "skills": ["Writing"], + "address": [ + "zip": "12342", + "city": "New York City" + ] +] + +let updated = original.merge(with: update) +// [ +// "first_name": "John", +// "last_name": "Doe", +// "age": 21, +// "skills": ["Coding", "Reading", "Writing"], +// "address": [ +// "street": "Front St", +// "zip": "12342", +// "city": "New York City" +// ] +// ] +``` + ## String representation There are two options available: - use the default Swift one From c4a4de08b0f9413466aa224755dcd52ba830cf18 Mon Sep 17 00:00:00 2001 From: Daniel Kiedrowski Date: Tue, 22 Nov 2016 11:00:07 +0100 Subject: [PATCH 108/260] Added pull request #725 to change log. --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b15b869..779cc304 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,7 +40,9 @@ - Allow .number to parse number from string instead of just numberValue [\#219](https://github.com/SwiftyJSON/SwiftyJSON/pull/219) ([yonaskolb](https://github.com/yonaskolb)) -- Fixed spelling and grammar mistakes in README.md. Made some swift syntax... [\#214](https://github.com/SwiftyJSON/SwiftyJSON/pull/214) ([pRizz](https://github.com/pRizz)) +- Fixed spelling and grammar mistakes in README.md. Made some swift syntax... [\#214](https://github.com/SwiftyJSON/SwiftyJSON/pull/725) ([danielkiedrowski](https://github.com/danielkiedrowski)) + +- Added a function to deep merge a JSON object into another JSON object... [\#725](https://github.com/SwiftyJSON/SwiftyJSON/pull/219) ([yonaskolb](https://github.com/yonaskolb)) ## [2.2.0](https://github.com/SwiftyJSON/SwiftyJSON/tree/2.2.0) (2015-04-13) From b35672498e5e5c6bcda8e088d9453eb6b7d289f7 Mon Sep 17 00:00:00 2001 From: Daniel Kiedrowski Date: Tue, 22 Nov 2016 11:04:12 +0100 Subject: [PATCH 109/260] Corrected commit #c4a4de0. Sorry. --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 779cc304..6a0935d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,9 +40,9 @@ - Allow .number to parse number from string instead of just numberValue [\#219](https://github.com/SwiftyJSON/SwiftyJSON/pull/219) ([yonaskolb](https://github.com/yonaskolb)) -- Fixed spelling and grammar mistakes in README.md. Made some swift syntax... [\#214](https://github.com/SwiftyJSON/SwiftyJSON/pull/725) ([danielkiedrowski](https://github.com/danielkiedrowski)) +- Fixed spelling and grammar mistakes in README.md. Made some swift syntax... [\#214](https://github.com/SwiftyJSON/SwiftyJSON/pull/214) ([pRizz](https://github.com/pRizz)) -- Added a function to deep merge a JSON object into another JSON object... [\#725](https://github.com/SwiftyJSON/SwiftyJSON/pull/219) ([yonaskolb](https://github.com/yonaskolb)) +- Added a function to deep merge a JSON object into another JSON object... [\#725](https://github.com/SwiftyJSON/SwiftyJSON/pull/725) ([danielkiedrowski](https://github.com/danielkiedrowski)) ## [2.2.0](https://github.com/SwiftyJSON/SwiftyJSON/tree/2.2.0) (2015-04-13) From 361356df1c66e4079425614a6d2d6d4f96845de2 Mon Sep 17 00:00:00 2001 From: Daniel Kiedrowski Date: Tue, 22 Nov 2016 11:35:20 +0100 Subject: [PATCH 110/260] Updated TOC of README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a7dac962..b103b826 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. - [Setter](#setter) - [Raw object](#raw-object) - [Literal convertibles](#literal-convertibles) + - [Merging](#merging) 5. [Work with Alamofire](#work-with-alamofire) > For Legacy Swift support, take a look at the [swift2 branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift2) From ae338a61420df6fc06f7d85fe7c219d8ad243ae8 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 23 Nov 2016 23:21:53 +0800 Subject: [PATCH 111/260] Update scripts --- scripts/ci.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/ci.sh b/scripts/ci.sh index 98277210..6c0a3a2d 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -2,8 +2,8 @@ set -e -xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON iOS" -destination "platform=iOS Simulator,name=iPhone 6" test +travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON iOS" -destination "platform=iOS Simulator,name=iPhone 6" build-for-testing test | xcpretty -xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON OSX" test +travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON OSX" build-for-testing test | xcpretty -xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON tvOS" -destination "platform=tvOS Simulator,name=Apple TV 1080p" test \ No newline at end of file +travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON tvOS" -destination "platform=tvOS Simulator,name=Apple TV 1080p" build-for-testing test | xcpretty From 493d6ba4ff6ccb3aa2bac06dad43b326b878da86 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Thu, 24 Nov 2016 00:42:23 +0800 Subject: [PATCH 112/260] Fix travis_retry command not found --- .travis.yml | 5 ++++- scripts/ci.sh | 9 --------- 2 files changed, 4 insertions(+), 10 deletions(-) delete mode 100755 scripts/ci.sh diff --git a/.travis.yml b/.travis.yml index c65386a0..63840195 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,10 @@ before_deploy: - carthage build --no-skip-current - carthage archive $FRAMEWORK_NAME script: -- sh scripts/ci.sh +- set -o pipefail +- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON iOS" -destination "platform=iOS Simulator,name=iPhone 6" build-for-testing test | xcpretty +- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON OSX" build-for-testing test | xcpretty +- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON tvOS" -destination "platform=tvOS Simulator,name=Apple TV 1080p" build-for-testing test | xcpretty deploy: provider: releases api_key: diff --git a/scripts/ci.sh b/scripts/ci.sh deleted file mode 100755 index 6c0a3a2d..00000000 --- a/scripts/ci.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash - -set -e - -travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON iOS" -destination "platform=iOS Simulator,name=iPhone 6" build-for-testing test | xcpretty - -travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON OSX" build-for-testing test | xcpretty - -travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON tvOS" -destination "platform=tvOS Simulator,name=Apple TV 1080p" build-for-testing test | xcpretty From 950c01f2fb3f12ecffccbe4ce780889e9d352eda Mon Sep 17 00:00:00 2001 From: Daniel Kiedrowski Date: Fri, 2 Dec 2016 11:30:28 +0100 Subject: [PATCH 113/260] Added a security mechanism to prevent total overwriting of the source JSON in case that the JSON differ in type on the top level. --- Source/SwiftyJSON.swift | 40 ++++++++++++++++---------- Tests/SwiftyJSONTests/MergeTests.swift | 7 +++++ 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 03dcc0f6..6719aa10 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -131,20 +131,7 @@ public struct JSON { - parameter other: The JSON which gets merged into this JSON */ public mutating func merge(with other: JSON) { - if self.type == other.type { - switch self.type { - case .dictionary: - for (key, _) in other { - self[key].merge(with: other[key]) - } - case .array: - self = JSON(self.arrayValue + other.arrayValue) - default: - self = other - } - } else { - self = other - } + self.merge(with: other, typecheck: true) } /** @@ -156,9 +143,32 @@ public struct JSON { */ public func merged(with other: JSON) -> JSON { var merged = self - merged.merge(with: other) + merged.merge(with: other, typecheck: true) return merged } + + // Private woker function which does the actual merging + // Typecheck is set to true for the first recursion level to prevent total override of the source JSON + private mutating func merge(with other: JSON, typecheck: Bool) { + if self.type == other.type { + switch self.type { + case .dictionary: + for (key, _) in other { + self[key].merge(with: other[key], typecheck: false) + } + case .array: + self = JSON(self.arrayValue + other.arrayValue) + default: + self = other + } + } else { + if typecheck { + print("Couldn't merge, because the JSONs differ in type on top level.") + } else { + self = other + } + } + } /// Private object fileprivate var rawArray: [Any] = [] diff --git a/Tests/SwiftyJSONTests/MergeTests.swift b/Tests/SwiftyJSONTests/MergeTests.swift index 30aec15b..18d88a98 100644 --- a/Tests/SwiftyJSONTests/MergeTests.swift +++ b/Tests/SwiftyJSONTests/MergeTests.swift @@ -25,6 +25,13 @@ import XCTest import SwiftyJSON class JSONTests: XCTestCase { + + func testDifferingTypes() { + let A = JSON("a") + let B = JSON(1) + XCTAssertEqual(A.merged(with: B), A) + } + func testPrimitiveType() { let A = JSON("a") let B = JSON("b") From bdcf170b142a3d117395590acbc09e7c7b36089b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20B=C3=B8geskov?= Date: Fri, 2 Dec 2016 12:46:22 +0100 Subject: [PATCH 114/260] Created new init instead of multiple small ones. --- Source/SwiftyJSON.swift | 66 +++++++++++++++++++++++++++++++---------- 1 file changed, 51 insertions(+), 15 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index f74e21b5..d8311361 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -64,14 +64,46 @@ public struct JSON { - returns: The created JSON */ - public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { + public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { do { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) - self.init(object) + self.init(jsonObject: object) } catch let aError as NSError { if error != nil { error?.pointee = aError } + self.init(jsonObject: NSNull()) + } + } + + /** + Creates a JSON object + - parameter object: the object + - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` + - returns: the created JSON object + */ + public init(_ object: Any) { + switch object { + case let object as [JSON] where object.count > 0: + self.init(array: object) + case let object as [String: JSON] where object.count > 0: + self.init(dictionary: object) + case let object as Data: + self.init(data: object) + default: + self.init(jsonObject: object) + } + } + + /** + Parses the JSON string into a JSON object + - parameter json: the JSON string + - returns: the created JSON object + */ + public init(parseJSON json: String) { + if let data = json.data(using: .utf8) { + self.init(data) + } else { self.init(NSNull()) } } @@ -82,8 +114,9 @@ public struct JSON { - returns: The created JSON */ - public static func parse(_ string:String) -> JSON { - return string.data(using: String.Encoding.utf8) + @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") + public static func parse(json: String) -> JSON { + return json.data(using: String.Encoding.utf8) .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) } @@ -94,8 +127,8 @@ public struct JSON { - returns: The created JSON */ - public init(_ object: Any) { - self.object = object + private init(jsonObject: Any) { + self.object = jsonObject } /** @@ -105,8 +138,8 @@ public struct JSON { - returns: The created JSON */ - public init(_ jsonArray:[JSON]) { - self.init(jsonArray.map { $0.object }) + private init(array: [JSON]) { + self.init(array.map { $0.object }) } /** @@ -116,12 +149,13 @@ public struct JSON { - returns: The created JSON */ - public init(_ jsonDictionary:[String: JSON]) { - var dictionary = [String: Any](minimumCapacity: jsonDictionary.count) - for (key, json) in jsonDictionary { - dictionary[key] = json.object + private init(dictionary: [String: JSON]) { + var newDictionary = [String: Any](minimumCapacity: dictionary.count) + for (key, json) in dictionary { + newDictionary[key] = json.object } - self.init(dictionary) + + self.init(newDictionary) } /// Private object @@ -165,10 +199,10 @@ public struct JSON { _type = .number self.rawNumber = number } - case let string as String: + case let string as String: _type = .string self.rawString = string - case _ as NSNull: + case _ as NSNull: _type = .null case _ as [JSON]: _type = .array @@ -726,6 +760,8 @@ extension JSON { public var array: [JSON]? { get { if self.type == .array { + print(self.rawArray) + print(self.rawArray.map{ JSON($0) }) return self.rawArray.map{ JSON($0) } } else { return nil From f0f6ead40a1fb0e323da1d2b8765e1ffe1c79669 Mon Sep 17 00:00:00 2001 From: Daniel Kiedrowski Date: Sat, 3 Dec 2016 10:14:05 +0100 Subject: [PATCH 115/260] Use exceptions to communicate merging error to user, if he tries to merge JSONs differing in type on top level. --- Source/SwiftyJSON.swift | 16 ++++++++------- Tests/SwiftyJSONTests/MergeTests.swift | 28 +++++++++++++++++--------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 6719aa10..f2840328 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -129,9 +129,10 @@ public struct JSON { present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - parameter other: The JSON which gets merged into this JSON + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ - public mutating func merge(with other: JSON) { - self.merge(with: other, typecheck: true) + public mutating func merge(with other: JSON) throws { + try self.merge(with: other, typecheck: true) } /** @@ -140,21 +141,22 @@ public struct JSON { - parameter other: The JSON which gets merged into this JSON - returns: New merged JSON + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ - public func merged(with other: JSON) -> JSON { + public func merged(with other: JSON) throws -> JSON { var merged = self - merged.merge(with: other, typecheck: true) + try merged.merge(with: other, typecheck: true) return merged } // Private woker function which does the actual merging // Typecheck is set to true for the first recursion level to prevent total override of the source JSON - private mutating func merge(with other: JSON, typecheck: Bool) { + private mutating func merge(with other: JSON, typecheck: Bool) throws { if self.type == other.type { switch self.type { case .dictionary: for (key, _) in other { - self[key].merge(with: other[key], typecheck: false) + try self[key].merge(with: other[key], typecheck: false) } case .array: self = JSON(self.arrayValue + other.arrayValue) @@ -163,7 +165,7 @@ public struct JSON { } } else { if typecheck { - print("Couldn't merge, because the JSONs differ in type on top level.") + throw NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]) } else { self = other } diff --git a/Tests/SwiftyJSONTests/MergeTests.swift b/Tests/SwiftyJSONTests/MergeTests.swift index 18d88a98..ddc4a24f 100644 --- a/Tests/SwiftyJSONTests/MergeTests.swift +++ b/Tests/SwiftyJSONTests/MergeTests.swift @@ -29,48 +29,58 @@ class JSONTests: XCTestCase { func testDifferingTypes() { let A = JSON("a") let B = JSON(1) - XCTAssertEqual(A.merged(with: B), A) + + do { + _ = try A.merged(with: B) + XCTFail() + } catch (let error) { + let error = error as NSError + XCTAssertEqual(error.code, ErrorWrongType) + XCTAssertEqual(error.domain, ErrorDomain) + XCTAssertEqual(error.userInfo[NSLocalizedDescriptionKey] as! String, + "Couldn't merge, because the JSONs differ in type on top level.") + } } func testPrimitiveType() { let A = JSON("a") let B = JSON("b") - XCTAssertEqual(A.merged(with: B), B) + XCTAssertEqual(try! A.merged(with: B), B) } func testMergeEqual() { let json = JSON(["a": "A"]) - XCTAssertEqual(json.merged(with: json), json) + XCTAssertEqual(try! json.merged(with: json), json) } func testMergeUnequalValues() { let A = JSON(["a": "A"]) let B = JSON(["a": "B"]) - XCTAssertEqual(A.merged(with: B), B) + XCTAssertEqual(try! A.merged(with: B), B) } func testMergeUnequalKeysAndValues() { let A = JSON(["a": "A"]) let B = JSON(["b": "B"]) - XCTAssertEqual(A.merged(with: B), JSON(["a": "A", "b": "B"])) + XCTAssertEqual(try! A.merged(with: B), JSON(["a": "A", "b": "B"])) } func testMergeFilledAndEmpty() { let A = JSON(["a": "A"]) let B = JSON([:]) - XCTAssertEqual(A.merged(with: B), A) + XCTAssertEqual(try! A.merged(with: B), A) } func testMergeEmptyAndFilled() { let A = JSON([:]) let B = JSON(["a": "A"]) - XCTAssertEqual(A.merged(with: B), B) + XCTAssertEqual(try! A.merged(with: B), B) } func testMergeArray() { let A = JSON(["a"]) let B = JSON(["b"]) - XCTAssertEqual(A.merged(with: B), JSON(["a", "b"])) + XCTAssertEqual(try! A.merged(with: B), JSON(["a", "b"])) } func testMergeNestedJSONs() { @@ -86,6 +96,6 @@ class JSONTests: XCTestCase { ] ]) - XCTAssertEqual(A.merged(with: B), B) + XCTAssertEqual(try! A.merged(with: B), B) } } From d2b4ae9ab4ba70bb37cd3e78639815075ac302ec Mon Sep 17 00:00:00 2001 From: Daniel Kiedrowski Date: Sat, 3 Dec 2016 10:21:55 +0100 Subject: [PATCH 116/260] Removed erroneous spaces and added spaces instead of tabs. --- README.md | 52 ++++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 736e0ee2..e6888341 100644 --- a/README.md +++ b/README.md @@ -452,43 +452,43 @@ If both JSONs contain a value for the same key, _mostly_ this value gets overwri - In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. - In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. -In case, where two fields in a JSON have a different types, the value will get always overwritten. +In case, where two fields in a JSON have a different types, the value will get always overwritten. -There are two different fashions for merging: `merge`modifies the original JSON, whereas `merged` works non-destructively on a copy. +There are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy. ```swift let original: JSON = [ - "first_name": "John", - "age": 20, - "skills": ["Coding", "Reading"], - "address": [ - "street": "Front St", - "zip": "12345", - ] + "first_name": "John", + "age": 20, + "skills": ["Coding", "Reading"], + "address": [ + "street": "Front St", + "zip": "12345", + ] ] let update: JSON = [ - "last_name": "Doe", - "age": 21, - "skills": ["Writing"], - "address": [ - "zip": "12342", - "city": "New York City" - ] + "last_name": "Doe", + "age": 21, + "skills": ["Writing"], + "address": [ + "zip": "12342", + "city": "New York City" + ] ] let updated = original.merge(with: update) // [ -// "first_name": "John", -// "last_name": "Doe", -// "age": 21, -// "skills": ["Coding", "Reading", "Writing"], -// "address": [ -// "street": "Front St", -// "zip": "12342", -// "city": "New York City" -// ] -// ] +// "first_name": "John", +// "last_name": "Doe", +// "age": 21, +// "skills": ["Coding", "Reading", "Writing"], +// "address": [ +// "street": "Front St", +// "zip": "12342", +// "city": "New York City" +// ] +// ] ``` ## String representation From 007d544ebd0bc429acc3b65680b291107ea0c684 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20B=C3=B8geskov?= Date: Mon, 5 Dec 2016 08:33:54 +0100 Subject: [PATCH 117/260] Removed print statements --- Source/SwiftyJSON.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index d8311361..9bf6cbf5 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -760,8 +760,6 @@ extension JSON { public var array: [JSON]? { get { if self.type == .array { - print(self.rawArray) - print(self.rawArray.map{ JSON($0) }) return self.rawArray.map{ JSON($0) } } else { return nil From ec2a1c7847e6da0165a1223754a73678c075257d Mon Sep 17 00:00:00 2001 From: looseyi <13615033587@126.com> Date: Thu, 8 Dec 2016 15:46:45 +0800 Subject: [PATCH 118/260] replace JSONRawIndex and JSONIndex with generics and desclear by typealise --- Source/SwiftyJSON.swift | 55 +++++++---------------------------------- 1 file changed, 9 insertions(+), 46 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index f2840328..ea8491b9 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -213,7 +213,7 @@ public struct JSON { _type = .number self.rawNumber = number } - case let string as String: + case let string as String: _type = .string self.rawString = string case _ as NSNull: @@ -247,16 +247,14 @@ public struct JSON { public static var null: JSON { get { return JSON(NSNull()) } } } -public enum JSONIndex:Comparable +public enum Index: Comparable { case array(Int) - case dictionary(DictionaryIndex) + case dictionary(DictionaryIndex) case null - static public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool - { - switch (lhs, rhs) - { + static public func ==(lhs: Index, rhs: Index) -> Bool { + switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): @@ -267,10 +265,8 @@ public enum JSONIndex:Comparable } } - static public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool - { - switch (lhs, rhs) - { + static public func <(lhs: Index, rhs: Index) -> Bool { + switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): @@ -279,44 +275,11 @@ public enum JSONIndex:Comparable return false } } - } -public enum JSONRawIndex: Comparable -{ - case array(Int) - case dictionary(DictionaryIndex) - case null +public typealias JSONIndex = Index +public typealias JSONRawIndex = Index - static public func ==(lhs: JSONRawIndex, rhs: JSONRawIndex) -> Bool - { - switch (lhs, rhs) - { - case (.array(let left), .array(let right)): - return left == right - case (.dictionary(let left), .dictionary(let right)): - return left == right - case (.null, .null): return true - default: - return false - } - } - - static public func <(lhs: JSONRawIndex, rhs: JSONRawIndex) -> Bool - { - switch (lhs, rhs) - { - case (.array(let left), .array(let right)): - return left < right - case (.dictionary(let left), .dictionary(let right)): - return left < right - default: - return false - } - } - - -} extension JSON: Collection { From fa439d70acd2df5c1c057ce5f519614ea8e88b2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20B=C3=B8geskov?= Date: Sat, 10 Dec 2016 09:27:45 +0100 Subject: [PATCH 119/260] Updated constructor to be more precise. --- Source/SwiftyJSON.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 9bf6cbf5..bb6e66b1 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -100,8 +100,8 @@ public struct JSON { - parameter json: the JSON string - returns: the created JSON object */ - public init(parseJSON json: String) { - if let data = json.data(using: .utf8) { + public init(parseJSON jsonString: String) { + if let data = jsonString.data(using: .utf8) { self.init(data) } else { self.init(NSNull()) From 7afc077db6cd7dad2e81388bc8c3b6e959f90c50 Mon Sep 17 00:00:00 2001 From: Yoshitaka Seki Date: Sun, 11 Dec 2016 20:29:10 +0900 Subject: [PATCH 120/260] Turn JSON.URL into lower-cased JSON.url --- Source/SwiftyJSON.swift | 2 +- Tests/SwiftyJSONTests/BaseTests.swift | 4 ++-- Tests/SwiftyJSONTests/StringTests.swift | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index f70e4f82..1e60cfb0 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -1010,7 +1010,7 @@ extension JSON { extension JSON { //Optional URL - public var URL: URL? { + public var url: URL? { get { switch self.type { case .string: diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift index 0ec670ed..47eb56f8 100644 --- a/Tests/SwiftyJSONTests/BaseTests.swift +++ b/Tests/SwiftyJSONTests/BaseTests.swift @@ -120,13 +120,13 @@ class BaseTests: XCTestCase { let user = json[0]["user"] let user_name = user["name"].string - let user_profile_image_url = user["profile_image_url"].URL + let user_profile_image_url = user["profile_image_url"].url XCTAssert(user_name == "OAuth Dancer") XCTAssert(user_profile_image_url == URL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) let user_dictionary = json[0]["user"].dictionary let user_dictionary_name = user_dictionary?["name"]?.string - let user_dictionary_name_profile_image_url = user_dictionary?["profile_image_url"]?.URL + let user_dictionary_name_profile_image_url = user_dictionary?["profile_image_url"]?.url XCTAssert(user_dictionary_name == "OAuth Dancer") XCTAssert(user_dictionary_name_profile_image_url == URL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) } diff --git a/Tests/SwiftyJSONTests/StringTests.swift b/Tests/SwiftyJSONTests/StringTests.swift index 9ba2b1df..d9d5508e 100644 --- a/Tests/SwiftyJSONTests/StringTests.swift +++ b/Tests/SwiftyJSONTests/StringTests.swift @@ -36,9 +36,9 @@ class StringTests: XCTestCase { XCTAssertEqual(json.stringValue, "12345?67890.@#") } - func testURL() { + func testUrl() { let json = JSON("http://github.com") - XCTAssertEqual(json.URL!, URL(string:"http://github.com")!) + XCTAssertEqual(json.url!, URL(string:"http://github.com")!) } func testBool() { @@ -56,15 +56,15 @@ class StringTests: XCTestCase { XCTAssertTrue(json.boolValue) } - func testURLPercentEscapes() { + func testUrlPercentEscapes() { let emDash = "\\u2014" let urlString = "http://examble.com/unencoded" + emDash + "string" guard let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return XCTFail("Couldn't encode URL string \(urlString)") } let json = JSON(urlString) - XCTAssertEqual(json.URL!, URL(string: encodedURLString)!, "Wrong unpacked ") + XCTAssertEqual(json.url!, URL(string: encodedURLString)!, "Wrong unpacked ") let preEscaped = JSON(encodedURLString) - XCTAssertEqual(preEscaped.URL!, URL(string: encodedURLString)!, "Wrong unpacked ") + XCTAssertEqual(preEscaped.url!, URL(string: encodedURLString)!, "Wrong unpacked ") } } From b311c581af557425db1cebfba2654c3b8b79ceea Mon Sep 17 00:00:00 2001 From: Jeff Kang Date: Fri, 16 Dec 2016 14:12:03 +0900 Subject: [PATCH 121/260] Add a title of NavigationBar with type --- Example/Example/ViewController.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index db1d1da1..3a35287c 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -29,6 +29,10 @@ class ViewController: UITableViewController { // MARK: - Table view data source + override func viewDidLoad() { + self.title = "SwiftyJSON(\(json.type))" + } + override func numberOfSections(in tableView: UITableView) -> Int { return 1 } From b295b6219cfbf8aac954c4471897ae8bb5754ba4 Mon Sep 17 00:00:00 2001 From: Naeem Shaikh Date: Fri, 16 Dec 2016 12:20:29 +0530 Subject: [PATCH 122/260] Update Work with Alamofire --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e6888341..b14c762e 100644 --- a/README.md +++ b/README.md @@ -507,7 +507,7 @@ let representation = json.rawString(options: [.castNilToNSNull: true]) SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: ```swift -Alamofire.request(.GET, url).validate().responseJSON { response in +Alamofire.request(url, method: .get).validate().responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) From 2c48d85304e0409e99a9ab584d3903dd2a6086ed Mon Sep 17 00:00:00 2001 From: Laurin Brandner Date: Wed, 21 Dec 2016 17:52:47 +0100 Subject: [PATCH 123/260] Convert to latest swift version --- Source/SwiftyJSON.swift | 14 +++++++------- SwiftyJSON.xcodeproj/project.pbxproj | 6 ++++-- Tests/SwiftyJSONTests/PrintableTests.swift | 4 ++-- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 1e60cfb0..f74ab534 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -115,7 +115,7 @@ public struct JSON { - returns: The created JSON */ @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") - public static func parse(json: String) -> JSON { + public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) } @@ -127,7 +127,7 @@ public struct JSON { - returns: The created JSON */ - private init(jsonObject: Any) { + fileprivate init(jsonObject: Any) { self.object = jsonObject } @@ -138,7 +138,7 @@ public struct JSON { - returns: The created JSON */ - private init(array: [JSON]) { + fileprivate init(array: [JSON]) { self.init(array.map { $0.object }) } @@ -149,7 +149,7 @@ public struct JSON { - returns: The created JSON */ - private init(dictionary: [String: JSON]) { + fileprivate init(dictionary: [String: JSON]) { var newDictionary = [String: Any](minimumCapacity: dictionary.count) for (key, json) in dictionary { newDictionary[key] = json.object @@ -185,7 +185,7 @@ public struct JSON { // Private woker function which does the actual merging // Typecheck is set to true for the first recursion level to prevent total override of the source JSON - private mutating func merge(with other: JSON, typecheck: Bool) throws { + fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { if self.type == other.type { switch self.type { case .dictionary: @@ -647,7 +647,7 @@ extension JSON: Swift.RawRepresentable { } } - public func rawString(options: [writtingOptionsKeys: Any]) -> String? { + public func rawString(_ options: [writtingOptionsKeys: Any]) -> String? { let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 do { @@ -658,7 +658,7 @@ extension JSON: Swift.RawRepresentable { } } - private func _rawString( + fileprivate func _rawString( _ encoding: String.Encoding = .utf8, options: [writtingOptionsKeys: Any], maxObjectDepth: Int = 10 diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index c4e6df5e..53df83b1 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -437,12 +437,12 @@ TargetAttributes = { 2E4FEFDA19575BE100351305 = { CreatedOnToolsVersion = 6.0; - LastSwiftMigration = 0800; + LastSwiftMigration = 0820; ProvisioningStyle = Automatic; }; 2E4FEFE519575BE100351305 = { CreatedOnToolsVersion = 6.0; - LastSwiftMigration = 0800; + LastSwiftMigration = 0820; ProvisioningStyle = Manual; TestTargetID = 2E4FEFDA19575BE100351305; }; @@ -819,6 +819,7 @@ METAL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -833,6 +834,7 @@ METAL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Release; }; diff --git a/Tests/SwiftyJSONTests/PrintableTests.swift b/Tests/SwiftyJSONTests/PrintableTests.swift index d8361685..bcdeaaae 100644 --- a/Tests/SwiftyJSONTests/PrintableTests.swift +++ b/Tests/SwiftyJSONTests/PrintableTests.swift @@ -76,7 +76,7 @@ class PrintableTests: XCTestCase { func testArrayWithOptionals() { let array = [1,2,"4",5,"6",nil] as [Any?] let json = JSON(array) - guard var description = json.rawString(options: [.castNilToNSNull: true]) else { + guard var description = json.rawString([.castNilToNSNull: true]) else { XCTFail("could not represent array") return } @@ -110,7 +110,7 @@ class PrintableTests: XCTestCase { func testDictionaryWithOptionals() { let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] let json = JSON(dict) - guard var description = json.rawString(options: [.castNilToNSNull: true]) else { + guard var description = json.rawString([.castNilToNSNull: true]) else { XCTFail("could not represent dictionary") return } From ad28952c6e370d6674be1e3e35149c9850b2d6d5 Mon Sep 17 00:00:00 2001 From: Laurin Brandner Date: Wed, 21 Dec 2016 17:53:18 +0100 Subject: [PATCH 124/260] Update to recommended proj settings --- SwiftyJSON.xcodeproj/project.pbxproj | 18 +++++++++--------- .../xcschemes/SwiftyJSON OSX.xcscheme | 2 +- .../xcschemes/SwiftyJSON iOS.xcscheme | 2 +- .../xcschemes/SwiftyJSON tvOS.xcscheme | 2 +- .../xcschemes/SwiftyJSON watchOS.xcscheme | 2 +- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 53df83b1..985b9fc5 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -433,7 +433,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0710; - LastUpgradeCheck = 0800; + LastUpgradeCheck = 0820; TargetAttributes = { 2E4FEFDA19575BE100351305 = { CreatedOnToolsVersion = 6.0; @@ -765,7 +765,7 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; @@ -787,7 +787,7 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; @@ -843,7 +843,7 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; DEFINES_MODULE = YES; DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; @@ -867,7 +867,7 @@ buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; DEFINES_MODULE = YES; DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; @@ -890,7 +890,7 @@ isa = XCBuildConfiguration; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; - CODE_SIGN_IDENTITY = "Mac Developer"; + CODE_SIGN_IDENTITY = ""; COMBINE_HIDPI_IMAGES = YES; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; @@ -918,7 +918,7 @@ isa = XCBuildConfiguration; buildSettings = { APPLICATION_EXTENSION_API_ONLY = YES; - CODE_SIGN_IDENTITY = "Mac Developer"; + CODE_SIGN_IDENTITY = ""; COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; @@ -1015,7 +1015,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; DEFINES_MODULE = YES; DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; @@ -1040,7 +1040,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; BITCODE_GENERATION_MODE = bitcode; CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; DEFINES_MODULE = YES; DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; diff --git a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme index 6d7a6f62..33f6b13c 100644 --- a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme +++ b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme @@ -1,6 +1,6 @@ Date: Wed, 21 Dec 2016 17:58:45 +0100 Subject: [PATCH 125/260] Convert every target --- Example/Example.xcodeproj/project.pbxproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index 717e1606..b114ac1e 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -129,7 +129,7 @@ TargetAttributes = { A82A1C1819D926B8009A653D = { CreatedOnToolsVersion = 6.0.1; - LastSwiftMigration = 0800; + LastSwiftMigration = 0820; ProvisioningStyle = Manual; }; }; From db78d800097d90b9e90274a04344d5f6551d83a7 Mon Sep 17 00:00:00 2001 From: kscheff Date: Thu, 22 Dec 2016 13:34:15 +0100 Subject: [PATCH 126/260] Update README.md The example seems to be wrongly assing the dictionary to the name data instead of dict. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b14c762e..6256c843 100644 --- a/README.md +++ b/README.md @@ -496,7 +496,7 @@ There are two options available: - use the default Swift one - use a custom one that will handle optionals well and represent `nil` as `"null"`: ```swift -let data = ["1":2, "2":"two", "3": nil] as [String: Any?] +let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] let json = JSON(dict) let representation = json.rawString(options: [.castNilToNSNull: true]) // representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} From 29a064b923b1199625b22334c4bc5f030bc85c25 Mon Sep 17 00:00:00 2001 From: "Robert M. Ryan" Date: Sun, 1 Jan 2017 21:33:57 -0800 Subject: [PATCH 127/260] Fix init(data:) error handling: The problem is that when users call `let json = JSON(data: data)`, they are not informed of the error, relying on the presence of `NSNull` value. That sort of use of non-standard sentinel value is discouraged. And the reliance of the `NSErrorPointer` is a pattern that pre-dates Swift 2 (and was intended for interacting with Objective-C API, not to be adopted within a Swift API itself). Bottom line, the error handling in `init(data:options:error:)` was distinctly unswifty. This attempts to remedy that. 1. Change init(data:options:) to throw errors, removing the `NSErrorPointer` reference. 2. Changed existing code that called `init(data:)` to reflect this error throwing behavior. 3. Also changed default reading options to be `[]` rather than `.allowFragments`, so that it's more consistent with standard `JSONSerialization` behavior. Also, I want to stop the perpetuation of the use of `.allowFragments` as a matter of standard practice, because generally if you have a fragment of JSON, you really want to know about that error. 4. Added test to demonstrate the catching of thrown error. --- Example/Playground.playground/Contents.swift | 6 ++-- Source/SwiftyJSON.swift | 23 ++++++------ Tests/SwiftyJSONTests/BaseTests.swift | 35 +++++++++++++++---- Tests/SwiftyJSONTests/PerformanceTests.swift | 26 +++++++++++--- Tests/SwiftyJSONTests/SequenceTypeTests.swift | 5 ++- 5 files changed, 67 insertions(+), 28 deletions(-) diff --git a/Example/Playground.playground/Contents.swift b/Example/Playground.playground/Contents.swift index 90b99433..87aebe68 100644 --- a/Example/Playground.playground/Contents.swift +++ b/Example/Playground.playground/Contents.swift @@ -31,7 +31,7 @@ let jsonString = String(data: jsonData!, encoding: .utf8) */ import SwiftyJSON -let json1 = JSON(data: jsonData!) +let json1 = try? JSON(data: jsonData!) /*: or */ @@ -40,7 +40,7 @@ let json2 = JSON(jsonObject) or */ let dataFromString = jsonString?.data(using: .utf8) -let json3 = JSON(data: dataFromString!) +let json3 = try? JSON(data: dataFromString!) /*: ### Subscript @@ -95,4 +95,4 @@ name = jsonArray[keys].string name = jsonArray["users"][1]["info"]["name"].string //Alternatively -name = jsonArray["users",1,"info","name"].string \ No newline at end of file +name = jsonArray["users",1,"info","name"].string diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index f74ab534..966098f3 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -59,21 +59,14 @@ public struct JSON { Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. + - parameter opt: The JSON serialization reading options. `[]` by default. - parameter error: The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ - public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { - do { - let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) - self.init(jsonObject: object) - } catch let aError as NSError { - if error != nil { - error?.pointee = aError - } - self.init(jsonObject: NSNull()) - } + public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { + let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) + self.init(jsonObject: object) } /** @@ -89,7 +82,11 @@ public struct JSON { case let object as [String: JSON] where object.count > 0: self.init(dictionary: object) case let object as Data: - self.init(data: object) + do { + try self.init(data: object) + } catch { + self.init(jsonObject: NSNull()) + } default: self.init(jsonObject: object) } @@ -117,7 +114,7 @@ public struct JSON { @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) - .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) + .flatMap{ try? JSON(data: $0) } ?? JSON(NSNull()) } /** diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift index 47eb56f8..60ed2f9f 100644 --- a/Tests/SwiftyJSONTests/BaseTests.swift +++ b/Tests/SwiftyJSONTests/BaseTests.swift @@ -43,7 +43,10 @@ class BaseTests: XCTestCase { } func testInit() { - let json0 = JSON(data:self.testData) + guard let json0 = try? JSON(data: self.testData) else { + XCTFail("Unable to parse testData") + return + } XCTAssertEqual(json0.array!.count, 3) XCTAssertEqual(JSON("123").description, "123") XCTAssertEqual(JSON(["1":"2"])["1"].string!, "2") @@ -76,7 +79,10 @@ class BaseTests: XCTestCase { } func testJSONDoesProduceValidWithCorrectKeyPath() { - let json = JSON(data:self.testData) + guard let json = try? JSON(data: self.testData) else { + XCTFail("Unable to parse testData") + return + } let tweets = json let tweets_array = json.array @@ -225,7 +231,10 @@ class BaseTests: XCTestCase { } func testErrorHandle() { - let json = JSON(data:self.testData) + guard let json = try? JSON(data: self.testData) else { + XCTFail("Unable to parse testData") + return + } if let _ = json["wrong-type"].string { XCTFail("Should not run into here") } else { @@ -245,11 +254,14 @@ class BaseTests: XCTestCase { } func testReturnObject() { - let json = JSON(data:self.testData) + guard let json = try? JSON(data: self.testData) else { + XCTFail("Unable to parse testData") + return + } XCTAssertNotNil(json.object) } - func testNumberCompare(){ + func testNumberCompare() { XCTAssertEqual(NSNumber(value: 888332), NSNumber(value:888332)) XCTAssertNotEqual(NSNumber(value: 888332.1), NSNumber(value:888332)) XCTAssertLessThan(NSNumber(value: 888332).doubleValue, NSNumber(value:888332.1).doubleValue) @@ -260,5 +272,16 @@ class BaseTests: XCTestCase { XCTAssertEqual(NSNumber(value: true), NSNumber(value:true)) } - + func testErrorThrowing() { + let invalidJson = "{\"foo\": 300]" // deliberately incorrect JSON + let invalidData = invalidJson.data(using: .utf8)! + + do { + let _ = try JSON(data: invalidData) + XCTFail("Should have thrown error; we should not have gotten here") + } catch { + // everything is OK + } + } + } diff --git a/Tests/SwiftyJSONTests/PerformanceTests.swift b/Tests/SwiftyJSONTests/PerformanceTests.swift index 80b3c028..4907cc65 100644 --- a/Tests/SwiftyJSONTests/PerformanceTests.swift +++ b/Tests/SwiftyJSONTests/PerformanceTests.swift @@ -45,14 +45,20 @@ class PerformanceTests: XCTestCase { func testInitPerformance() { self.measure() { for _ in 1...100 { - let json = JSON(data:self.testData) + guard let json = try? JSON(data: self.testData) else { + XCTFail("Unable to parse testData") + return + } XCTAssertTrue(json != JSON.null) } } } func testObjectMethodPerformance() { - let json = JSON(data:self.testData) + guard let json = try? JSON(data: self.testData) else { + XCTFail("Unable to parse testData") + return + } self.measure() { for _ in 1...100 { let object:Any? = json.object @@ -62,7 +68,10 @@ class PerformanceTests: XCTestCase { } func testArrayMethodPerformance() { - let json = JSON(data:self.testData) + guard let json = try? JSON(data: self.testData) else { + XCTFail("Unable to parse testData") + return + } self.measure() { for _ in 1...100 { autoreleasepool{ @@ -75,7 +84,11 @@ class PerformanceTests: XCTestCase { } func testDictionaryMethodPerformance() { - let json = JSON(data:testData)[0] + guard let json = try? JSON(data: self.testData)[0] else { + XCTFail("Unable to parse testData") + return + } + self.measure() { for _ in 1...100 { autoreleasepool{ @@ -88,7 +101,10 @@ class PerformanceTests: XCTestCase { } func testRawStringMethodPerformance() { - let json = JSON(data:testData) + guard let json = try? JSON(data: self.testData) else { + XCTFail("Unable to parse testData") + return + } self.measure() { for _ in 1...100 { autoreleasepool{ diff --git a/Tests/SwiftyJSONTests/SequenceTypeTests.swift b/Tests/SwiftyJSONTests/SequenceTypeTests.swift index 62bd7dcf..1cf8af3f 100644 --- a/Tests/SwiftyJSONTests/SequenceTypeTests.swift +++ b/Tests/SwiftyJSONTests/SequenceTypeTests.swift @@ -29,7 +29,10 @@ class SequenceTypeTests: XCTestCase { func testJSONFile() { if let file = Bundle(for:BaseTests.self).path(forResource: "Tests", ofType: "json") { let testData = try? Data(contentsOf: URL(fileURLWithPath: file)) - let json = JSON(data:testData!) + guard let json = try? JSON(data: testData!) else { + XCTFail("Unable to parse the data") + return + } for (index, sub) in json { switch (index as NSString).integerValue { case 0: From 94d7f0593a031811cfef7c803b335aa51600fe7a Mon Sep 17 00:00:00 2001 From: skyline75489 Date: Tue, 3 Jan 2017 09:34:20 +0800 Subject: [PATCH 128/260] Hello 2017 --- Source/SwiftyJSON.h | 2 +- Source/SwiftyJSON.swift | 2 +- Tests/SwiftyJSONTests/ArrayTests.swift | 2 +- Tests/SwiftyJSONTests/BaseTests.swift | 2 +- Tests/SwiftyJSONTests/ComparableTests.swift | 2 +- Tests/SwiftyJSONTests/DictionaryTests.swift | 2 +- Tests/SwiftyJSONTests/LiteralConvertibleTests.swift | 2 +- Tests/SwiftyJSONTests/NumberTests.swift | 2 +- Tests/SwiftyJSONTests/PerformanceTests.swift | 2 +- Tests/SwiftyJSONTests/PrintableTests.swift | 2 +- Tests/SwiftyJSONTests/RawRepresentableTests.swift | 2 +- Tests/SwiftyJSONTests/RawTests.swift | 2 +- Tests/SwiftyJSONTests/SequenceTypeTests.swift | 2 +- Tests/SwiftyJSONTests/StringTests.swift | 2 +- Tests/SwiftyJSONTests/SubscriptTests.swift | 2 +- 15 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Source/SwiftyJSON.h b/Source/SwiftyJSON.h index ac942218..d69a7643 100644 --- a/Source/SwiftyJSON.h +++ b/Source/SwiftyJSON.h @@ -1,6 +1,6 @@ // SwiftyJSON.h // -// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang +// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index f74ab534..e79c10d1 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -1,6 +1,6 @@ // SwiftyJSON.swift // -// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang +// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/ArrayTests.swift b/Tests/SwiftyJSONTests/ArrayTests.swift index e2d471a6..c3c53de3 100644 --- a/Tests/SwiftyJSONTests/ArrayTests.swift +++ b/Tests/SwiftyJSONTests/ArrayTests.swift @@ -1,6 +1,6 @@ // ArrayTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift index 47eb56f8..0c0ff8e5 100644 --- a/Tests/SwiftyJSONTests/BaseTests.swift +++ b/Tests/SwiftyJSONTests/BaseTests.swift @@ -1,6 +1,6 @@ // BaseTests.swift // -// Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang +// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/ComparableTests.swift b/Tests/SwiftyJSONTests/ComparableTests.swift index c027b07a..f238012f 100644 --- a/Tests/SwiftyJSONTests/ComparableTests.swift +++ b/Tests/SwiftyJSONTests/ComparableTests.swift @@ -1,6 +1,6 @@ // ComparableTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/DictionaryTests.swift b/Tests/SwiftyJSONTests/DictionaryTests.swift index 13208ded..5f9c822f 100644 --- a/Tests/SwiftyJSONTests/DictionaryTests.swift +++ b/Tests/SwiftyJSONTests/DictionaryTests.swift @@ -1,6 +1,6 @@ // DictionaryTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift b/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift index c55f2516..fa88e231 100644 --- a/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift +++ b/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift @@ -1,6 +1,6 @@ // LiteralConvertibleTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/NumberTests.swift b/Tests/SwiftyJSONTests/NumberTests.swift index 828bae68..0ae66b54 100644 --- a/Tests/SwiftyJSONTests/NumberTests.swift +++ b/Tests/SwiftyJSONTests/NumberTests.swift @@ -1,6 +1,6 @@ // NumberTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/PerformanceTests.swift b/Tests/SwiftyJSONTests/PerformanceTests.swift index 80b3c028..e3ed9760 100644 --- a/Tests/SwiftyJSONTests/PerformanceTests.swift +++ b/Tests/SwiftyJSONTests/PerformanceTests.swift @@ -1,6 +1,6 @@ // PerformanceTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/PrintableTests.swift b/Tests/SwiftyJSONTests/PrintableTests.swift index bcdeaaae..f60fc8c1 100644 --- a/Tests/SwiftyJSONTests/PrintableTests.swift +++ b/Tests/SwiftyJSONTests/PrintableTests.swift @@ -1,6 +1,6 @@ // PrintableTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/RawRepresentableTests.swift b/Tests/SwiftyJSONTests/RawRepresentableTests.swift index 342cd782..9ebf9b2e 100644 --- a/Tests/SwiftyJSONTests/RawRepresentableTests.swift +++ b/Tests/SwiftyJSONTests/RawRepresentableTests.swift @@ -1,6 +1,6 @@ // RawRepresentableTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/RawTests.swift b/Tests/SwiftyJSONTests/RawTests.swift index d45f1cec..7693d8e3 100644 --- a/Tests/SwiftyJSONTests/RawTests.swift +++ b/Tests/SwiftyJSONTests/RawTests.swift @@ -1,6 +1,6 @@ // RawTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/SequenceTypeTests.swift b/Tests/SwiftyJSONTests/SequenceTypeTests.swift index 62bd7dcf..8f164c4c 100644 --- a/Tests/SwiftyJSONTests/SequenceTypeTests.swift +++ b/Tests/SwiftyJSONTests/SequenceTypeTests.swift @@ -1,7 +1,7 @@ // // SequenceTypeTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/StringTests.swift b/Tests/SwiftyJSONTests/StringTests.swift index d9d5508e..8d8e6ebc 100644 --- a/Tests/SwiftyJSONTests/StringTests.swift +++ b/Tests/SwiftyJSONTests/StringTests.swift @@ -1,6 +1,6 @@ // StringTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/Tests/SwiftyJSONTests/SubscriptTests.swift b/Tests/SwiftyJSONTests/SubscriptTests.swift index e9acc8c1..2a5cd97e 100644 --- a/Tests/SwiftyJSONTests/SubscriptTests.swift +++ b/Tests/SwiftyJSONTests/SubscriptTests.swift @@ -1,6 +1,6 @@ // SubscriptTests.swift // -// Copyright (c) 2014 - 2016 Pinglin Tang +// Copyright (c) 2014 - 2017 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal From dadbfcffd5f51e2b488a26e83f188d96755e5393 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 10 Jan 2017 17:35:24 +0800 Subject: [PATCH 129/260] Bump version to 3.1.4 --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 111a6976..2d822e31 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "3.1.3" + s.version = "3.1.4" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } From a76d81d3c8ac68e52ada6c74fd6eca2b6082f757 Mon Sep 17 00:00:00 2001 From: Craig Grummitt Date: Tue, 10 Jan 2017 13:42:36 -0500 Subject: [PATCH 130/260] Fixed Spelling mistake - writing has one 't' --- Source/SwiftyJSON.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index e79c10d1..14a1e60c 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -647,7 +647,7 @@ extension JSON: Swift.RawRepresentable { } } - public func rawString(_ options: [writtingOptionsKeys: Any]) -> String? { + public func rawString(_ options: [writingOptionsKeys: Any]) -> String? { let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 do { @@ -660,7 +660,7 @@ extension JSON: Swift.RawRepresentable { fileprivate func _rawString( _ encoding: String.Encoding = .utf8, - options: [writtingOptionsKeys: Any], + options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10 ) throws -> String? { if (maxObjectDepth < 0) { @@ -1477,7 +1477,7 @@ func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { } } -public enum writtingOptionsKeys { +public enum writingOptionsKeys { case jsonSerialization case castNilToNSNull case maxObjextDepth From 1c5e9025062dd521fe6cb30ae9f20828ad08ece7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=81=E5=B8=85?= Date: Sat, 4 Feb 2017 16:03:12 +0800 Subject: [PATCH 131/260] fix nested JSON problems with JSON initialize method --- Source/SwiftyJSON.swift | 132 +++++++----------------- SwiftyJSON.xcodeproj/project.pbxproj | 4 + Tests/SwiftyJSONTests/NestedTests.swift | 53 ++++++++++ 3 files changed, 93 insertions(+), 96 deletions(-) create mode 100644 Tests/SwiftyJSONTests/NestedTests.swift diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 14a1e60c..72aeb717 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -84,10 +84,6 @@ public struct JSON { */ public init(_ object: Any) { switch object { - case let object as [JSON] where object.count > 0: - self.init(array: object) - case let object as [String: JSON] where object.count > 0: - self.init(dictionary: object) case let object as Data: self.init(data: object) default: @@ -130,33 +126,6 @@ public struct JSON { fileprivate init(jsonObject: Any) { self.object = jsonObject } - - /** - Creates a JSON from a [JSON] - - - parameter jsonArray: A Swift array of JSON objects - - - returns: The created JSON - */ - fileprivate init(array: [JSON]) { - self.init(array.map { $0.object }) - } - - /** - Creates a JSON from a [String: JSON] - - - parameter jsonDictionary: A Swift dictionary of JSON objects - - - returns: The created JSON - */ - fileprivate init(dictionary: [String: JSON]) { - var newDictionary = [String: Any](minimumCapacity: dictionary.count) - for (key, json) in dictionary { - newDictionary[key] = json.object - } - - self.init(newDictionary) - } /** Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, @@ -238,7 +207,7 @@ public struct JSON { } set { _error = nil - switch newValue { + switch unwrap(newValue) { case let number as NSNumber: if number.isBool { _type = .bool @@ -252,10 +221,8 @@ public struct JSON { self.rawString = string case _ as NSNull: _type = .null - case _ as [JSON]: - _type = .array - case nil: - _type = .null + case nil: + _type = .null case let array as [Any]: _type = .array self.rawArray = array @@ -281,8 +248,25 @@ public struct JSON { public static var null: JSON { get { return JSON(NSNull()) } } } -public enum Index: Comparable -{ +// unwrap nested JSON +private func unwrap(_ object: Any) -> Any { + switch object { + case let json as JSON: + return unwrap(json.object) + case let array as [Any]: + return array.map(unwrap) + case let dictionary as [String : Any]: + var unwrapedDic = dictionary + for (k, v) in dictionary { + unwrapedDic[k] = unwrap(v) + } + return unwrapedDic + default: + return object + } +} + +public enum Index: Comparable { case array(Int) case dictionary(DictionaryIndex) case null @@ -314,16 +298,12 @@ public enum Index: Comparable public typealias JSONIndex = Index public typealias JSONRawIndex = Index - -extension JSON: Collection -{ +extension JSON: Swift.Collection { public typealias Index = JSONRawIndex - public var startIndex: Index - { - switch type - { + public var startIndex: Index { + switch type { case .array: return .array(rawArray.startIndex) case .dictionary: @@ -333,10 +313,8 @@ extension JSON: Collection } } - public var endIndex: Index - { - switch type - { + public var endIndex: Index { + switch type { case .array: return .array(rawArray.endIndex) case .dictionary: @@ -346,10 +324,8 @@ extension JSON: Collection } } - public func index(after i: Index) -> Index - { - switch i - { + public func index(after i: Index) -> Index { + switch i { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): @@ -357,13 +333,10 @@ extension JSON: Collection default: return .null } - } - public subscript (position: Index) -> (String, JSON) - { - switch position - { + public subscript (position: Index) -> (String, JSON) { + switch position { case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): @@ -373,8 +346,6 @@ extension JSON: Collection return ("", JSON.null) } } - - } // MARK: - Subscript @@ -382,8 +353,7 @@ extension JSON: Collection /** * To mark both String and Int can be used in subscript. */ -public enum JSONKey -{ +public enum JSONKey { case index(Int) case key(String) } @@ -561,41 +531,11 @@ extension JSON: Swift.ExpressibleByFloatLiteral { extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { - let array = elements - self.init(dictionaryLiteral: array) - } - - public init(dictionaryLiteral elements: [(String, Any)]) { - let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in - let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in - if let value = dictionary[key] { - return (key, value) - } - return nil - } - return JSON(dictionaryLiteral: initializeElement) - } - - var dict = [String : Any](minimumCapacity: elements.count) - - for element in elements { - let elementToSet: Any - if let json = element.1 as? JSON { - elementToSet = json.object - } else if let jsonArray = element.1 as? [JSON] { - elementToSet = JSON(jsonArray).object - } else if let dictionary = element.1 as? [String : Any] { - elementToSet = jsonFromDictionaryLiteral(dictionary).object - } else if let dictArray = element.1 as? [[String : Any]] { - let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) } - elementToSet = JSON(jsonArray).object - } else { - elementToSet = element.1 - } - dict[element.0] = elementToSet + var dictionary = [String : Any](minimumCapacity: elements.count) + for (k, v) in elements { + dictionary[k] = v } - - self.init(dict) + self.init(dictionary as Any) } } diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 985b9fc5..dd7a4035 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 170ECF711E45BFF500FD325C /* NestedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 170ECF701E45BFF500FD325C /* NestedTests.swift */; }; 1B587CC61DDE04770012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; 1B587CC71DDE04780012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; 1B587CC81DDE04790012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; @@ -94,6 +95,7 @@ /* Begin PBXFileReference section */ 030B6CDC1A6E171D00C2D4F1 /* Info-OSX.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-OSX.plist"; sourceTree = ""; }; + 170ECF701E45BFF500FD325C /* NestedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NestedTests.swift; sourceTree = ""; }; 1B587CC41DDE04360012D8DB /* MergeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MergeTests.swift; sourceTree = ""; }; 2E4FEFDB19575BE100351305 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 2E4FEFDF19575BE100351305 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; @@ -246,6 +248,7 @@ A863BE2719EED46F0092A41F /* RawTests.swift */, A8B66C8B19E51D6500540692 /* DictionaryTests.swift */, A8B66C8D19E52F4200540692 /* ArrayTests.swift */, + 170ECF701E45BFF500FD325C /* NestedTests.swift */, 2E4FEFEB19575BE100351305 /* Supporting Files */, ); name = SwiftyJSONTests; @@ -563,6 +566,7 @@ A819C49919E1B10300ADCC3D /* RawRepresentableTests.swift in Sources */, A819C49F19E2EE5B00ADCC3D /* SubscriptTests.swift in Sources */, A863BE2819EED46F0092A41F /* RawTests.swift in Sources */, + 170ECF711E45BFF500FD325C /* NestedTests.swift in Sources */, A885D1D219CF1EE6002FD4C3 /* BaseTests.swift in Sources */, A8B66C8E19E52F4200540692 /* ArrayTests.swift in Sources */, A8B66C8C19E51D6500540692 /* DictionaryTests.swift in Sources */, diff --git a/Tests/SwiftyJSONTests/NestedTests.swift b/Tests/SwiftyJSONTests/NestedTests.swift new file mode 100644 index 00000000..0de5448c --- /dev/null +++ b/Tests/SwiftyJSONTests/NestedTests.swift @@ -0,0 +1,53 @@ +// +// NestedTests.swift +// SwiftyJSON +// +// Created by 丁帅 on 2017/2/4. +// +// + +import XCTest +import SwiftyJSON + +class NestedTests: XCTestCase { + + func testArrayJSON() { + let arr: [JSON] = ["a", 1, ["b", 2]] + let json = JSON(arr) + XCTAssertEqual(json[0].string, "a") + XCTAssertEqual(json[2,1].int, 2) + } + + func testDictionaryJSON() { + let json: JSON = ["a": JSON("1"), "b": JSON([1, 2, "3"]), "c": JSON(["aa": "11", "bb": 22])] + XCTAssertEqual(json["a"].string, "1") + XCTAssertEqual(json["b"].array!, [1, 2, "3"]) + XCTAssertEqual(json["c"]["aa"].string, "11") + + print(json["b"].arrayObject!) + } + + func testNextedJSON() { + let inner = JSON.init([ + "some_field": "1" + "2", + ]) + + let json = JSON.init([ + "outer_field": "1" + "2", + "inner_json": inner + ]) + + XCTAssertEqual(json["inner_json"], ["some_field": "12"]) + + let foo = "foo" + + let json2 = JSON.init([ + "outer_field": foo, + "inner_json": inner + ]) + + XCTAssertEqual(json2["inner_json"], ["some_field": "12"]) + + } + +} From 19d5cd3809d73f8f932b6699fc84f8755063045c Mon Sep 17 00:00:00 2001 From: Humoud Date: Sun, 12 Feb 2017 14:41:04 +0300 Subject: [PATCH 132/260] add Work with Moya section to README.MD --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index 6256c843..6c462346 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. - [Literal convertibles](#literal-convertibles) - [Merging](#merging) 5. [Work with Alamofire](#work-with-alamofire) +6. [Work with Moya](#work-with-moya) > For Legacy Swift support, take a look at the [swift2 branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift2) @@ -517,3 +518,23 @@ Alamofire.request(url, method: .get).validate().responseJSON { response in } } ``` + + +## Work with Moya + +SwiftyJSON parse data to JSON: + +```swift +let provider = MoyaProvider() +provider.request(.showProducts) { result in + switch result { + case let .success(moyaResponse): + let data = moyaResponse.data + let json = JSON(data: data) // convert network data to json + print(json) + case let .failure(error): + print("error: \(error)") + } +} + +``` From fcd1c6796777349662ead65bda2507354387514d Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Mon, 13 Feb 2017 22:25:45 +0800 Subject: [PATCH 133/260] [Optimization] Update LLVM and Swift compiler level --- SwiftyJSON.xcodeproj/project.pbxproj | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 985b9fc5..183662cd 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -771,6 +771,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_OPTIMIZATION_LEVEL = 0; INFOPLIST_FILE = "Source/Info-iOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; @@ -778,6 +779,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; }; name = Debug; @@ -793,6 +795,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_OPTIMIZATION_LEVEL = s; INFOPLIST_FILE = "Source/Info-iOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; @@ -809,6 +812,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; DEVELOPMENT_TEAM = ""; + GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", @@ -819,6 +823,7 @@ METAL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; }; name = Debug; @@ -828,6 +833,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; DEVELOPMENT_TEAM = ""; + GCC_OPTIMIZATION_LEVEL = s; INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-iOS.plist"; IPHONEOS_DEPLOYMENT_TARGET = 9.1; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -849,6 +855,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_OPTIMIZATION_LEVEL = 0; INFOPLIST_FILE = "Source/Info-tvOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; @@ -857,6 +864,7 @@ PRODUCT_NAME = SwiftyJSON; SDKROOT = appletvos; SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; TARGETED_DEVICE_FAMILY = 3; TVOS_DEPLOYMENT_TARGET = 9.0; }; @@ -873,6 +881,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_OPTIMIZATION_LEVEL = s; INFOPLIST_FILE = "Source/Info-tvOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; @@ -897,6 +906,7 @@ DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; FRAMEWORK_VERSION = A; + GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", @@ -911,6 +921,7 @@ PRODUCT_NAME = "$(PROJECT_NAME)"; SDKROOT = macosx; SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; @@ -926,6 +937,7 @@ DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; FRAMEWORK_VERSION = A; + GCC_OPTIMIZATION_LEVEL = s; INFOPLIST_FILE = "Source/Info-OSX.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; @@ -945,6 +957,7 @@ CODE_SIGN_IDENTITY = ""; COMBINE_HIDPI_IMAGES = YES; FRAMEWORK_SEARCH_PATHS = ""; + GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", @@ -956,6 +969,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; @@ -966,6 +980,7 @@ COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; FRAMEWORK_SEARCH_PATHS = ""; + GCC_OPTIMIZATION_LEVEL = s; INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-OSX.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; @@ -982,12 +997,14 @@ CODE_SIGN_IDENTITY = ""; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-tvOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.tangplin.SwiftyJSON-tvOS-Tests"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; TVOS_DEPLOYMENT_TARGET = 9.0; }; name = Debug; @@ -999,6 +1016,7 @@ COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = s; INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-tvOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = NO; @@ -1021,6 +1039,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_OPTIMIZATION_LEVEL = 0; INFOPLIST_FILE = "Source/Info-OSX.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1029,6 +1048,7 @@ SDKROOT = watchos; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; TARGETED_DEVICE_FAMILY = 4; WATCHOS_DEPLOYMENT_TARGET = 2.0; }; @@ -1046,6 +1066,7 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_OPTIMIZATION_LEVEL = s; INFOPLIST_FILE = "Source/Info-OSX.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; From 78470aa6f0f72b3f202acee395f1e77e1dd29717 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=81=E5=B8=85?= Date: Thu, 16 Feb 2017 18:20:40 +0800 Subject: [PATCH 134/260] rawValue test --- Tests/SwiftyJSONTests/NestedTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/SwiftyJSONTests/NestedTests.swift b/Tests/SwiftyJSONTests/NestedTests.swift index 0de5448c..6a136043 100644 --- a/Tests/SwiftyJSONTests/NestedTests.swift +++ b/Tests/SwiftyJSONTests/NestedTests.swift @@ -46,7 +46,7 @@ class NestedTests: XCTestCase { "inner_json": inner ]) - XCTAssertEqual(json2["inner_json"], ["some_field": "12"]) + XCTAssertEqual(json2["inner_json"].rawValue as! [String : String], ["some_field": "12"]) } From d91b9ecb28bf962290061e0a3e94c9231c28a09d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=81=E5=B8=85?= Date: Fri, 17 Feb 2017 15:08:56 +0800 Subject: [PATCH 135/260] Fix a spelling mistake and merge duplicate test files --- Source/SwiftyJSON.swift | 6 +-- SwiftyJSON.xcodeproj/project.pbxproj | 4 -- Tests/SwiftyJSONTests/NestedJSONTests.swift | 32 +++++++++++++ Tests/SwiftyJSONTests/NestedTests.swift | 53 --------------------- 4 files changed, 35 insertions(+), 60 deletions(-) delete mode 100644 Tests/SwiftyJSONTests/NestedTests.swift diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 72aeb717..43931cce 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -256,11 +256,11 @@ private func unwrap(_ object: Any) -> Any { case let array as [Any]: return array.map(unwrap) case let dictionary as [String : Any]: - var unwrapedDic = dictionary + var unwrappedDic = dictionary for (k, v) in dictionary { - unwrapedDic[k] = unwrap(v) + unwrappedDic[k] = unwrap(v) } - return unwrapedDic + return unwrappedDic default: return object } diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index dd7a4035..985b9fc5 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -7,7 +7,6 @@ objects = { /* Begin PBXBuildFile section */ - 170ECF711E45BFF500FD325C /* NestedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 170ECF701E45BFF500FD325C /* NestedTests.swift */; }; 1B587CC61DDE04770012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; 1B587CC71DDE04780012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; 1B587CC81DDE04790012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; @@ -95,7 +94,6 @@ /* Begin PBXFileReference section */ 030B6CDC1A6E171D00C2D4F1 /* Info-OSX.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-OSX.plist"; sourceTree = ""; }; - 170ECF701E45BFF500FD325C /* NestedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NestedTests.swift; sourceTree = ""; }; 1B587CC41DDE04360012D8DB /* MergeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MergeTests.swift; sourceTree = ""; }; 2E4FEFDB19575BE100351305 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 2E4FEFDF19575BE100351305 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; @@ -248,7 +246,6 @@ A863BE2719EED46F0092A41F /* RawTests.swift */, A8B66C8B19E51D6500540692 /* DictionaryTests.swift */, A8B66C8D19E52F4200540692 /* ArrayTests.swift */, - 170ECF701E45BFF500FD325C /* NestedTests.swift */, 2E4FEFEB19575BE100351305 /* Supporting Files */, ); name = SwiftyJSONTests; @@ -566,7 +563,6 @@ A819C49919E1B10300ADCC3D /* RawRepresentableTests.swift in Sources */, A819C49F19E2EE5B00ADCC3D /* SubscriptTests.swift in Sources */, A863BE2819EED46F0092A41F /* RawTests.swift in Sources */, - 170ECF711E45BFF500FD325C /* NestedTests.swift in Sources */, A885D1D219CF1EE6002FD4C3 /* BaseTests.swift in Sources */, A8B66C8E19E52F4200540692 /* ArrayTests.swift in Sources */, A8B66C8C19E51D6500540692 /* DictionaryTests.swift in Sources */, diff --git a/Tests/SwiftyJSONTests/NestedJSONTests.swift b/Tests/SwiftyJSONTests/NestedJSONTests.swift index 5c75def7..17305384 100644 --- a/Tests/SwiftyJSONTests/NestedJSONTests.swift +++ b/Tests/SwiftyJSONTests/NestedJSONTests.swift @@ -39,4 +39,36 @@ class NestedJSONTests: XCTestCase { ] XCTAssertNotNil(try? nestedFamily.rawData()) } + + func testArrayJSON() { + let arr: [JSON] = ["a", 1, ["b", 2]] + let json = JSON(arr) + XCTAssertEqual(json[0].string, "a") + XCTAssertEqual(json[2,1].int, 2) + } + + func testDictionaryJSON() { + let json: JSON = ["a": JSON("1"), "b": JSON([1, 2, "3"]), "c": JSON(["aa": "11", "bb": 22])] + XCTAssertEqual(json["a"].string, "1") + XCTAssertEqual(json["b"].array!, [1, 2, "3"]) + XCTAssertEqual(json["c"]["aa"].string, "11") + } + + func testNextedJSON() { + let inner = JSON.init([ + "some_field": "1" + "2", + ]) + let json = JSON.init([ + "outer_field": "1" + "2", + "inner_json": inner + ]) + XCTAssertEqual(json["inner_json"], ["some_field": "12"]) + + let foo = "foo" + let json2 = JSON.init([ + "outer_field": foo, + "inner_json": inner + ]) + XCTAssertEqual(json2["inner_json"].rawValue as! [String : String], ["some_field": "12"]) + } } diff --git a/Tests/SwiftyJSONTests/NestedTests.swift b/Tests/SwiftyJSONTests/NestedTests.swift deleted file mode 100644 index 6a136043..00000000 --- a/Tests/SwiftyJSONTests/NestedTests.swift +++ /dev/null @@ -1,53 +0,0 @@ -// -// NestedTests.swift -// SwiftyJSON -// -// Created by 丁帅 on 2017/2/4. -// -// - -import XCTest -import SwiftyJSON - -class NestedTests: XCTestCase { - - func testArrayJSON() { - let arr: [JSON] = ["a", 1, ["b", 2]] - let json = JSON(arr) - XCTAssertEqual(json[0].string, "a") - XCTAssertEqual(json[2,1].int, 2) - } - - func testDictionaryJSON() { - let json: JSON = ["a": JSON("1"), "b": JSON([1, 2, "3"]), "c": JSON(["aa": "11", "bb": 22])] - XCTAssertEqual(json["a"].string, "1") - XCTAssertEqual(json["b"].array!, [1, 2, "3"]) - XCTAssertEqual(json["c"]["aa"].string, "11") - - print(json["b"].arrayObject!) - } - - func testNextedJSON() { - let inner = JSON.init([ - "some_field": "1" + "2", - ]) - - let json = JSON.init([ - "outer_field": "1" + "2", - "inner_json": inner - ]) - - XCTAssertEqual(json["inner_json"], ["some_field": "12"]) - - let foo = "foo" - - let json2 = JSON.init([ - "outer_field": foo, - "inner_json": inner - ]) - - XCTAssertEqual(json2["inner_json"].rawValue as! [String : String], ["some_field": "12"]) - - } - -} From 9d96db2a1627709c90ed144dcf2e60dfdd73c762 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Fri, 17 Feb 2017 22:46:42 +0800 Subject: [PATCH 136/260] [SwiftLint] Add SwiftLint target --- SwiftyJSON.xcodeproj/project.pbxproj | 57 ++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 183662cd..cf25aa14 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -6,6 +6,20 @@ objectVersion = 46; objects = { +/* Begin PBXAggregateTarget section */ + A81D162B1E5743B000C62C5F /* SwiftLint */ = { + isa = PBXAggregateTarget; + buildConfigurationList = A81D162E1E5743B000C62C5F /* Build configuration list for PBXAggregateTarget "SwiftLint" */; + buildPhases = ( + A81D162F1E5743CE00C62C5F /* ShellScript */, + ); + dependencies = ( + ); + name = SwiftLint; + productName = SwiftLint; + }; +/* End PBXAggregateTarget section */ + /* Begin PBXBuildFile section */ 1B587CC61DDE04770012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; 1B587CC71DDE04780012D8DB /* MergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B587CC41DDE04360012D8DB /* MergeTests.swift */; }; @@ -456,6 +470,10 @@ 9C7DFC641A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; }; + A81D162B1E5743B000C62C5F = { + CreatedOnToolsVersion = 8.2.1; + ProvisioningStyle = Automatic; + }; A8580F731BCF5C5B00DA927B = { CreatedOnToolsVersion = 7.1; }; @@ -483,6 +501,7 @@ E4D7CCDE1B9465A700EE7221 /* SwiftyJSON watchOS */, 7236B4EC1BAC14150020529B /* SwiftyJSON tvOS */, A8580F731BCF5C5B00DA927B /* SwiftyJSON tvOS Tests */, + A81D162B1E5743B000C62C5F /* SwiftLint */, ); }; /* End PBXProject section */ @@ -542,6 +561,22 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + A81D162F1E5743CE00C62C5F /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\nswiftlint\nelse\necho \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi"; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 2E4FEFD619575BE100351305 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -991,6 +1026,20 @@ }; name = Release; }; + A81D162C1E5743B000C62C5F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + A81D162D1E5743B000C62C5F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; A8580F7D1BCF5C5B00DA927B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -1137,6 +1186,14 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + A81D162E1E5743B000C62C5F /* Build configuration list for PBXAggregateTarget "SwiftLint" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A81D162C1E5743B000C62C5F /* Debug */, + A81D162D1E5743B000C62C5F /* Release */, + ); + defaultConfigurationIsVisible = 0; + }; A8580F7C1BCF5C5B00DA927B /* Build configuration list for PBXNativeTarget "SwiftyJSON tvOS Tests" */ = { isa = XCConfigurationList; buildConfigurations = ( From 5acb5d76655f5bf81dd258b18662f72fcd3964d0 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Fri, 17 Feb 2017 22:47:29 +0800 Subject: [PATCH 137/260] [SwiftLint] add .swiftlint.yml --- .swiftlint.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 .swiftlint.yml diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 00000000..e69de29b From 395124dcf6f220980bc065f3b94402f2119c7fe0 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Fri, 17 Feb 2017 22:55:59 +0800 Subject: [PATCH 138/260] [SwiftLint] Autocorrect code style --- .swiftlint.yml | 13 + Example/Example/AppDelegate.swift | 7 +- Example/Example/ViewController.swift | 10 +- Example/Playground.playground/Contents.swift | 4 +- Source/SwiftyJSON.swift | 92 +++--- Tests/SwiftyJSONTests/ArrayTests.swift | 6 +- Tests/SwiftyJSONTests/BaseTests.swift | 147 +++++----- Tests/SwiftyJSONTests/ComparableTests.swift | 273 +++++++++--------- Tests/SwiftyJSONTests/DictionaryTests.swift | 12 +- .../LiteralConvertibleTests.swift | 34 +-- Tests/SwiftyJSONTests/MergeTests.swift | 24 +- Tests/SwiftyJSONTests/NestedJSONTests.swift | 16 +- Tests/SwiftyJSONTests/NumberTests.swift | 85 +++--- Tests/SwiftyJSONTests/PerformanceTests.swift | 36 +-- Tests/SwiftyJSONTests/PrintableTests.swift | 32 +- .../RawRepresentableTests.swift | 38 +-- Tests/SwiftyJSONTests/RawTests.swift | 28 +- Tests/SwiftyJSONTests/SequenceTypeTests.swift | 34 +-- Tests/SwiftyJSONTests/StringTests.swift | 2 +- Tests/SwiftyJSONTests/SubscriptTests.swift | 164 +++++------ 20 files changed, 524 insertions(+), 533 deletions(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index e69de29b..1a5ad564 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -0,0 +1,13 @@ +disabled_rules: + - force_cast + - force_try + - variable_name + - type_name + - file_length + - line_length + - type_body_length + - implicit_getter + - operator_whitespace + - cyclomatic_complexity + - function_body_length + - control_statement diff --git a/Example/Example/AppDelegate.swift b/Example/Example/AppDelegate.swift index 6c0aead8..f0e91456 100644 --- a/Example/Example/AppDelegate.swift +++ b/Example/Example/AppDelegate.swift @@ -29,10 +29,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { - + let navigationController = self.window?.rootViewController as! UINavigationController let viewController = navigationController.topViewController as! ViewController - + if let file = Bundle.main.path(forResource: "SwiftyJSONTests", ofType: "json") { do { let data = try Data(contentsOf: URL(fileURLWithPath: file)) @@ -44,8 +44,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } else { viewController.json = JSON.null } - + return true } } - diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index db1d1da1..b2145e7d 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -26,7 +26,7 @@ import SwiftyJSON class ViewController: UITableViewController { var json: JSON = JSON.null - + // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { @@ -44,9 +44,9 @@ class ViewController: UITableViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "JSONCell", for: indexPath) as UITableViewCell - + let row = (indexPath as NSIndexPath).row - + switch self.json.type { case .array: cell.textLabel?.text = "\(row)" @@ -60,7 +60,7 @@ class ViewController: UITableViewController { cell.textLabel?.text = "" cell.detailTextLabel?.text = self.json.description } - + return cell } @@ -70,7 +70,7 @@ class ViewController: UITableViewController { var nextController: UIViewController? nextController = segue.destination - + if let indexPath = self.tableView.indexPathForSelectedRow { let row = (indexPath as NSIndexPath).row var nextJson: JSON = JSON.null diff --git a/Example/Playground.playground/Contents.swift b/Example/Playground.playground/Contents.swift index 90b99433..6c9f5361 100644 --- a/Example/Playground.playground/Contents.swift +++ b/Example/Playground.playground/Contents.swift @@ -85,7 +85,7 @@ jsonDictionary["country"].stringValue //Getting a string using a path to the element let path = ["users", 1, "info", "name"] as [JSONSubscriptType] -var name = jsonArray["users",1,"info","name"].string +var name = jsonArray["users", 1, "info", "name"].string //With a custom way let keys: [JSONSubscriptType] = ["users", 1, "info", "name"] @@ -95,4 +95,4 @@ name = jsonArray[keys].string name = jsonArray["users"][1]["info"]["name"].string //Alternatively -name = jsonArray["users",1,"info","name"].string \ No newline at end of file +name = jsonArray["users", 1, "info", "name"].string diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 14a1e60c..8cd2d86e 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -41,7 +41,7 @@ public let ErrorInvalidJSON: Int = 490 See http://www.json.org */ -public enum Type :Int{ +public enum Type: Int { case number case string @@ -117,7 +117,7 @@ public struct JSON { @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) - .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) + .flatMap { JSON(data: $0) } ?? JSON(NSNull()) } /** @@ -157,7 +157,7 @@ public struct JSON { self.init(newDictionary) } - + /** Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. @@ -168,7 +168,7 @@ public struct JSON { public mutating func merge(with other: JSON) throws { try self.merge(with: other, typecheck: true) } - + /** Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. @@ -182,7 +182,7 @@ public struct JSON { try merged.merge(with: other, typecheck: true) return merged } - + // Private woker function which does the actual merging // Typecheck is set to true for the first recursion level to prevent total override of the source JSON fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { @@ -216,7 +216,7 @@ public struct JSON { /// Private type fileprivate var _type: Type = .null /// prviate error - fileprivate var _error: NSError? = nil + fileprivate var _error: NSError? /// Object in JSON public var object: Any { @@ -281,8 +281,7 @@ public struct JSON { public static var null: JSON { get { return JSON(NSNull()) } } } -public enum Index: Comparable -{ +public enum Index: Comparable { case array(Int) case dictionary(DictionaryIndex) case null @@ -314,16 +313,12 @@ public enum Index: Comparable public typealias JSONIndex = Index public typealias JSONRawIndex = Index - -extension JSON: Collection -{ +extension JSON: Collection { public typealias Index = JSONRawIndex - public var startIndex: Index - { - switch type - { + public var startIndex: Index { + switch type { case .array: return .array(rawArray.startIndex) case .dictionary: @@ -333,10 +328,8 @@ extension JSON: Collection } } - public var endIndex: Index - { - switch type - { + public var endIndex: Index { + switch type { case .array: return .array(rawArray.endIndex) case .dictionary: @@ -346,10 +339,8 @@ extension JSON: Collection } } - public func index(after i: Index) -> Index - { - switch i - { + public func index(after i: Index) -> Index { + switch i { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): @@ -360,10 +351,8 @@ extension JSON: Collection } - public subscript (position: Index) -> (String, JSON) - { - switch position - { + public subscript (position: Index) -> (String, JSON) { + switch position { case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): @@ -374,7 +363,6 @@ extension JSON: Collection } } - } // MARK: - Subscript @@ -382,24 +370,23 @@ extension JSON: Collection /** * To mark both String and Int can be used in subscript. */ -public enum JSONKey -{ +public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { - var jsonKey:JSONKey { get } + var jsonKey: JSONKey { get } } extension Int: JSONSubscriptType { - public var jsonKey:JSONKey { + public var jsonKey: JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { - public var jsonKey:JSONKey { + public var jsonKey: JSONKey { return JSONKey.key(self) } } @@ -417,7 +404,7 @@ extension JSON { return JSON(self.rawArray[index]) } else { var r = JSON.null - r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) + r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return r } } @@ -576,7 +563,7 @@ extension JSON: Swift.ExpressibleByDictionaryLiteral { return JSON(dictionaryLiteral: initializeElement) } - var dict = [String : Any](minimumCapacity: elements.count) + var dict = [String: Any](minimumCapacity: elements.count) for element in elements { let elementToSet: Any @@ -637,7 +624,7 @@ extension JSON: Swift.RawRepresentable { return try JSONSerialization.data(withJSONObject: self.object, options: opt) } - + public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { do { return try _rawString(encoding, options: [.jsonSerialization: opt]) @@ -771,7 +758,7 @@ extension JSON { public var array: [JSON]? { get { if self.type == .array { - return self.rawArray.map{ JSON($0) } + return self.rawArray.map { JSON($0) } } else { return nil } @@ -812,7 +799,7 @@ extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { - var d = [String : JSON](minimumCapacity: rawDictionary.count) + var d = [String: JSON](minimumCapacity: rawDictionary.count) for (key, value) in rawDictionary { d[key] = JSON(value) } @@ -880,7 +867,7 @@ extension JSON { // : Swift.Bool case .number: return self.rawNumber.boolValue case .string: - return ["true", "y", "t"].contains() { (truthyString) in + return ["true", "y", "t"].contains { (truthyString) in return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame } default: @@ -980,7 +967,7 @@ extension JSON { } } -//MARK: - Null +// MARK: - Null extension JSON { public var null: NSNull? { @@ -996,7 +983,7 @@ extension JSON { self.object = NSNull() } } - public func exists() -> Bool{ + public func exists() -> Bool { if let errorValue = error, errorValue.code == ErrorNotExist || errorValue.code == ErrorIndexOutOfBounds || errorValue.code == ErrorWrongType { @@ -1006,7 +993,7 @@ extension JSON { } } -//MARK: - URL +// MARK: - URL extension JSON { //Optional URL @@ -1081,19 +1068,14 @@ extension JSON { } } - public var int: Int? - { - get - { + public var int: Int? { + get { return self.number?.intValue } - set - { - if let newValue = newValue - { + set { + if let newValue = newValue { self.object = NSNumber(value: newValue) - } else - { + } else { self.object = NSNull() } } @@ -1307,7 +1289,7 @@ extension JSON { } } -//MARK: - Comparable +// MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { @@ -1402,10 +1384,10 @@ private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { - var isBool:Bool { + var isBool: Bool { get { let objCType = String(cString: self.objCType) - if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){ + if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { return true } else { return false diff --git a/Tests/SwiftyJSONTests/ArrayTests.swift b/Tests/SwiftyJSONTests/ArrayTests.swift index c3c53de3..0c955e7d 100644 --- a/Tests/SwiftyJSONTests/ArrayTests.swift +++ b/Tests/SwiftyJSONTests/ArrayTests.swift @@ -26,7 +26,7 @@ import SwiftyJSON class ArrayTests: XCTestCase { func testSingleDimensionalArraysGetter() { - let array = ["1","2", "a", "B", "D"] + let array = ["1", "2", "a", "B", "D"] let json = JSON(array) XCTAssertEqual((json.array![0] as JSON).string!, "1") XCTAssertEqual((json.array![1] as JSON).string!, "2") @@ -34,9 +34,9 @@ class ArrayTests: XCTestCase { XCTAssertEqual((json.array![3] as JSON).string!, "B") XCTAssertEqual((json.array![4] as JSON).string!, "D") } - + func testSingleDimensionalArraysSetter() { - let array = ["1","2", "a", "B", "D"] + let array = ["1", "2", "a", "B", "D"] var json = JSON(array) json.arrayObject = ["111", "222"] XCTAssertEqual((json.array![0] as JSON).string!, "111") diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift index 0c0ff8e5..80bb9893 100644 --- a/Tests/SwiftyJSONTests/BaseTests.swift +++ b/Tests/SwiftyJSONTests/BaseTests.swift @@ -26,27 +26,27 @@ import XCTest class BaseTests: XCTestCase { var testData: Data! - + override func setUp() { - + super.setUp() - + if let file = Bundle(for:BaseTests.self).path(forResource: "Tests", ofType: "json") { self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { XCTFail("Can't find the test JSON file") } } - + override func tearDown() { super.tearDown() } - + func testInit() { let json0 = JSON(data:self.testData) XCTAssertEqual(json0.array!.count, 3) XCTAssertEqual(JSON("123").description, "123") - XCTAssertEqual(JSON(["1":"2"])["1"].string!, "2") + XCTAssertEqual(JSON(["1": "2"])["1"].string!, "2") let dictionary = NSMutableDictionary() dictionary.setObject(NSNumber(value: 1.0), forKey: "number" as NSString) dictionary.setObject(NSNull(), forKey: "null" as NSString) @@ -58,26 +58,26 @@ class BaseTests: XCTestCase { } catch _ { } } - + func testCompare() { XCTAssertNotEqual(JSON("32.1234567890"), JSON(32.1234567890)) - let veryLargeNumber:UInt64 = 9876543210987654321 - XCTAssertNotEqual(JSON("9876543210987654321"),JSON(NSNumber(value:veryLargeNumber))) + let veryLargeNumber: UInt64 = 9876543210987654321 + XCTAssertNotEqual(JSON("9876543210987654321"), JSON(NSNumber(value:veryLargeNumber))) XCTAssertNotEqual(JSON("9876543210987654321.12345678901234567890"), JSON(9876543210987654321.12345678901234567890)) XCTAssertEqual(JSON("😊"), JSON("😊")) XCTAssertNotEqual(JSON("😱"), JSON("😁")) - XCTAssertEqual(JSON([123,321,456]), JSON([123,321,456])) - XCTAssertNotEqual(JSON([123,321,456]), JSON(123456789)) - XCTAssertNotEqual(JSON([123,321,456]), JSON("string")) - XCTAssertNotEqual(JSON(["1":123,"2":321,"3":456]), JSON("string")) - XCTAssertEqual(JSON(["1":123,"2":321,"3":456]), JSON(["2":321,"1":123,"3":456])) - XCTAssertEqual(JSON(NSNull()),JSON(NSNull())) + XCTAssertEqual(JSON([123, 321, 456]), JSON([123, 321, 456])) + XCTAssertNotEqual(JSON([123, 321, 456]), JSON(123456789)) + XCTAssertNotEqual(JSON([123, 321, 456]), JSON("string")) + XCTAssertNotEqual(JSON(["1": 123, "2": 321, "3": 456]), JSON("string")) + XCTAssertEqual(JSON(["1": 123, "2": 321, "3": 456]), JSON(["2": 321, "1": 123, "3": 456])) + XCTAssertEqual(JSON(NSNull()), JSON(NSNull())) XCTAssertNotEqual(JSON(NSNull()), JSON(123)) } - + func testJSONDoesProduceValidWithCorrectKeyPath() { let json = JSON(data:self.testData) - + let tweets = json let tweets_array = json.array let tweets_1 = json[1] @@ -89,12 +89,12 @@ class BaseTests: XCTestCase { XCTAssertNotEqual(tweets_1.type, Type.null) XCTAssertEqual(tweets_1_user_name, JSON("Raffi Krikorian")) XCTAssertEqual(tweets_1_user_name_string!, "Raffi Krikorian") - + let tweets_1_coordinates = tweets_1["coordinates"] let tweets_1_coordinates_coordinates = tweets_1_coordinates["coordinates"] let tweets_1_coordinates_coordinates_point_0_double = tweets_1_coordinates_coordinates[0].double let tweets_1_coordinates_coordinates_point_1_float = tweets_1_coordinates_coordinates[1].float - let new_tweets_1_coordinates_coordinates = JSON([-122.25831,37.871609] as NSArray) + let new_tweets_1_coordinates_coordinates = JSON([-122.25831, 37.871609] as NSArray) XCTAssertEqual(tweets_1_coordinates_coordinates, new_tweets_1_coordinates_coordinates) XCTAssertEqual(tweets_1_coordinates_coordinates_point_0_double!, -122.25831) XCTAssertTrue(tweets_1_coordinates_coordinates_point_1_float! == 37.871609) @@ -106,16 +106,16 @@ class BaseTests: XCTestCase { let tweets_1_coordinates_coordinates_point_1 = tweets_1_coordinates_coordinates[1] XCTAssertEqual(tweets_1_coordinates_coordinates_point_0, JSON(-122.25831)) XCTAssertEqual(tweets_1_coordinates_coordinates_point_1, JSON(37.871609)) - + let created_at = json[0]["created_at"].string let id_str = json[0]["id_str"].string let favorited = json[0]["favorited"].bool let id = json[0]["id"].int64 let in_reply_to_user_id_str = json[0]["in_reply_to_user_id_str"] XCTAssertEqual(created_at!, "Tue Aug 28 21:16:23 +0000 2012") - XCTAssertEqual(id_str!,"240558470661799936") + XCTAssertEqual(id_str!, "240558470661799936") XCTAssertFalse(favorited!) - XCTAssertEqual(id!,240558470661799936) + XCTAssertEqual(id!, 240558470661799936) XCTAssertEqual(in_reply_to_user_id_str.type, Type.null) let user = json[0]["user"] @@ -130,7 +130,7 @@ class BaseTests: XCTestCase { XCTAssert(user_dictionary_name == "OAuth Dancer") XCTAssert(user_dictionary_name_profile_image_url == URL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) } - + func testJSONNumberCompare() { XCTAssertEqual(JSON(12376352.123321), JSON(12376352.123321)) XCTAssertGreaterThan(JSON(20.211), JSON(20.112)) @@ -139,7 +139,7 @@ class BaseTests: XCTestCase { XCTAssertLessThan(JSON(-82320.211), JSON(20.112)) XCTAssertLessThanOrEqual(JSON(-320.211), JSON(123.1)) XCTAssertLessThanOrEqual(JSON(-8763), JSON(-8763)) - + XCTAssertEqual(JSON(12376352.123321), JSON(12376352.123321)) XCTAssertGreaterThan(JSON(20.211), JSON(20.112)) XCTAssertGreaterThanOrEqual(JSON(30.211), JSON(20.112)) @@ -149,81 +149,81 @@ class BaseTests: XCTestCase { XCTAssertLessThanOrEqual(JSON(-8763), JSON(-8763)) } - func testNumberConvertToString(){ + func testNumberConvertToString() { XCTAssertEqual(JSON(true).stringValue, "true") XCTAssertEqual(JSON(999.9823).stringValue, "999.9823") XCTAssertEqual(JSON(true).number!.stringValue, "1") XCTAssertEqual(JSON(false).number!.stringValue, "0") XCTAssertEqual(JSON("hello").numberValue.stringValue, "0") XCTAssertEqual(JSON(NSNull()).numberValue.stringValue, "0") - XCTAssertEqual(JSON(["a","b","c","d"]).numberValue.stringValue, "0") - XCTAssertEqual(JSON(["a":"b","c":"d"]).numberValue.stringValue, "0") + XCTAssertEqual(JSON(["a", "b", "c", "d"]).numberValue.stringValue, "0") + XCTAssertEqual(JSON(["a": "b", "c": "d"]).numberValue.stringValue, "0") } - - func testNumberPrint(){ - XCTAssertEqual(JSON(false).description,"false") - XCTAssertEqual(JSON(true).description,"true") + func testNumberPrint() { - XCTAssertEqual(JSON(1).description,"1") - XCTAssertEqual(JSON(22).description,"22") + XCTAssertEqual(JSON(false).description, "false") + XCTAssertEqual(JSON(true).description, "true") + + XCTAssertEqual(JSON(1).description, "1") + XCTAssertEqual(JSON(22).description, "22") #if (arch(x86_64) || arch(arm64)) - XCTAssertEqual(JSON(9.22337203685478E18).description,"9.22337203685478e+18") + XCTAssertEqual(JSON(9.22337203685478E18).description, "9.22337203685478e+18") #elseif (arch(i386) || arch(arm)) - XCTAssertEqual(JSON(2147483647).description,"2147483647") + XCTAssertEqual(JSON(2147483647).description, "2147483647") #endif - XCTAssertEqual(JSON(-1).description,"-1") - XCTAssertEqual(JSON(-934834834).description,"-934834834") - XCTAssertEqual(JSON(-2147483648).description,"-2147483648") - - XCTAssertEqual(JSON(1.5555).description,"1.5555") - XCTAssertEqual(JSON(-9.123456789).description,"-9.123456789") - XCTAssertEqual(JSON(-0.00000000000000001).description,"-1e-17") - XCTAssertEqual(JSON(-999999999999999999999999.000000000000000000000001).description,"-1e+24") - XCTAssertEqual(JSON(-9999999991999999999999999.88888883433343439438493483483943948341).stringValue,"-9.999999991999999e+24") - - XCTAssertEqual(JSON(Int(Int.max)).description,"\(Int.max)") - XCTAssertEqual(JSON(NSNumber(value: Int.min)).description,"\(Int.min)") - XCTAssertEqual(JSON(NSNumber(value: UInt.max)).description,"\(UInt.max)") - XCTAssertEqual(JSON(NSNumber(value: UInt64.max)).description,"\(UInt64.max)") - XCTAssertEqual(JSON(NSNumber(value: Int64.max)).description,"\(Int64.max)") - XCTAssertEqual(JSON(NSNumber(value: UInt64.max)).description,"\(UInt64.max)") - - XCTAssertEqual(JSON(Double.infinity).description,"inf") - XCTAssertEqual(JSON(-Double.infinity).description,"-inf") - XCTAssertEqual(JSON(Double.nan).description,"nan") - - XCTAssertEqual(JSON(1.0/0.0).description,"inf") - XCTAssertEqual(JSON(-1.0/0.0).description,"-inf") - XCTAssertEqual(JSON(0.0/0.0).description,"nan") + XCTAssertEqual(JSON(-1).description, "-1") + XCTAssertEqual(JSON(-934834834).description, "-934834834") + XCTAssertEqual(JSON(-2147483648).description, "-2147483648") + + XCTAssertEqual(JSON(1.5555).description, "1.5555") + XCTAssertEqual(JSON(-9.123456789).description, "-9.123456789") + XCTAssertEqual(JSON(-0.00000000000000001).description, "-1e-17") + XCTAssertEqual(JSON(-999999999999999999999999.000000000000000000000001).description, "-1e+24") + XCTAssertEqual(JSON(-9999999991999999999999999.88888883433343439438493483483943948341).stringValue, "-9.999999991999999e+24") + + XCTAssertEqual(JSON(Int(Int.max)).description, "\(Int.max)") + XCTAssertEqual(JSON(NSNumber(value: Int.min)).description, "\(Int.min)") + XCTAssertEqual(JSON(NSNumber(value: UInt.max)).description, "\(UInt.max)") + XCTAssertEqual(JSON(NSNumber(value: UInt64.max)).description, "\(UInt64.max)") + XCTAssertEqual(JSON(NSNumber(value: Int64.max)).description, "\(Int64.max)") + XCTAssertEqual(JSON(NSNumber(value: UInt64.max)).description, "\(UInt64.max)") + + XCTAssertEqual(JSON(Double.infinity).description, "inf") + XCTAssertEqual(JSON(-Double.infinity).description, "-inf") + XCTAssertEqual(JSON(Double.nan).description, "nan") + + XCTAssertEqual(JSON(1.0/0.0).description, "inf") + XCTAssertEqual(JSON(-1.0/0.0).description, "-inf") + XCTAssertEqual(JSON(0.0/0.0).description, "nan") } - + func testNullJSON() { - XCTAssertEqual(JSON(NSNull()).debugDescription,"null") - - let json:JSON = JSON.null - XCTAssertEqual(json.debugDescription,"null") + XCTAssertEqual(JSON(NSNull()).debugDescription, "null") + + let json: JSON = JSON.null + XCTAssertEqual(json.debugDescription, "null") XCTAssertNil(json.error) - let json1:JSON = JSON(NSNull()) + let json1: JSON = JSON(NSNull()) if json1 != JSON.null { XCTFail("json1 should be nil") } } - + func testExistance() { - let dictionary = ["number":1111] + let dictionary = ["number": 1111] let json = JSON(dictionary) XCTAssertFalse(json["unspecifiedValue"].exists()) XCTAssertFalse(json[0].exists()) XCTAssertTrue(json["number"].exists()) - let array = [["number":1111]] + let array = [["number": 1111]] let jsonForArray = JSON(array) XCTAssertTrue(jsonForArray[0].exists()) XCTAssertFalse(jsonForArray[1].exists()) XCTAssertFalse(jsonForArray["someValue"].exists()) } - + func testErrorHandle() { let json = JSON(data:self.testData) if let _ = json["wrong-type"].string { @@ -237,19 +237,19 @@ class BaseTests: XCTestCase { } else { XCTAssertEqual(json[0]["not-exist"].error!.code, SwiftyJSON.ErrorNotExist) } - + let wrongJSON = JSON(NSObject()) if let error = wrongJSON.error { XCTAssertEqual(error.code, SwiftyJSON.ErrorUnsupportedType) } } - + func testReturnObject() { let json = JSON(data:self.testData) XCTAssertNotNil(json.object) } - - func testNumberCompare(){ + + func testNumberCompare() { XCTAssertEqual(NSNumber(value: 888332), NSNumber(value:888332)) XCTAssertNotEqual(NSNumber(value: 888332.1), NSNumber(value:888332)) XCTAssertLessThan(NSNumber(value: 888332).doubleValue, NSNumber(value:888332.1).doubleValue) @@ -259,6 +259,5 @@ class BaseTests: XCTestCase { XCTAssertEqual(NSNumber(value: false), NSNumber(value:false)) XCTAssertEqual(NSNumber(value: true), NSNumber(value:true)) } - } diff --git a/Tests/SwiftyJSONTests/ComparableTests.swift b/Tests/SwiftyJSONTests/ComparableTests.swift index f238012f..1f8343e9 100644 --- a/Tests/SwiftyJSONTests/ComparableTests.swift +++ b/Tests/SwiftyJSONTests/ComparableTests.swift @@ -26,279 +26,278 @@ import SwiftyJSON class ComparableTests: XCTestCase { func testNumberEqual() { - let jsonL1:JSON = 1234567890.876623 - let jsonR1:JSON = JSON(1234567890.876623) + let jsonL1: JSON = 1234567890.876623 + let jsonR1: JSON = JSON(1234567890.876623) XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 == 1234567890.876623) - let jsonL2:JSON = 987654321 - let jsonR2:JSON = JSON(987654321) + let jsonL2: JSON = 987654321 + let jsonR2: JSON = JSON(987654321) XCTAssertEqual(jsonL2, jsonR2) XCTAssertTrue(jsonR2 == 987654321) - - let jsonL3:JSON = JSON(NSNumber(value:87654321.12345678)) - let jsonR3:JSON = JSON(NSNumber(value:87654321.12345678)) + let jsonL3: JSON = JSON(NSNumber(value:87654321.12345678)) + let jsonR3: JSON = JSON(NSNumber(value:87654321.12345678)) XCTAssertEqual(jsonL3, jsonR3) XCTAssertTrue(jsonR3 == 87654321.12345678) } - + func testNumberNotEqual() { - let jsonL1:JSON = 1234567890.876623 - let jsonR1:JSON = JSON(123.123) + let jsonL1: JSON = 1234567890.876623 + let jsonR1: JSON = JSON(123.123) XCTAssertNotEqual(jsonL1, jsonR1) XCTAssertFalse(jsonL1 == 34343) - - let jsonL2:JSON = 8773 - let jsonR2:JSON = JSON(123.23) + + let jsonL2: JSON = 8773 + let jsonR2: JSON = JSON(123.23) XCTAssertNotEqual(jsonL2, jsonR2) XCTAssertFalse(jsonR1 == 454352) - - let jsonL3:JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3:JSON = JSON(NSNumber(value:87654321.45678)) + + let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value:87654321.45678)) XCTAssertNotEqual(jsonL3, jsonR3) XCTAssertFalse(jsonL3 == 4545.232) } - + func testNumberGreaterThanOrEqual() { - let jsonL1:JSON = 1234567890.876623 - let jsonR1:JSON = JSON(123.123) + let jsonL1: JSON = 1234567890.876623 + let jsonR1: JSON = JSON(123.123) XCTAssertGreaterThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 >= -37434) - - let jsonL2:JSON = 8773 - let jsonR2:JSON = JSON(-87343) + + let jsonL2: JSON = 8773 + let jsonR2: JSON = JSON(-87343) XCTAssertGreaterThanOrEqual(jsonL2, jsonR2) XCTAssertTrue(jsonR2 >= -988343) - let jsonL3:JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3:JSON = JSON(NSNumber(value:87621.12345678)) + let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value:87621.12345678)) XCTAssertGreaterThanOrEqual(jsonL3, jsonR3) XCTAssertTrue(jsonR3 >= 0.3232) } - + func testNumberLessThanOrEqual() { - let jsonL1:JSON = 1234567890.876623 - let jsonR1:JSON = JSON(123.123) + let jsonL1: JSON = 1234567890.876623 + let jsonR1: JSON = JSON(123.123) XCTAssertLessThanOrEqual(jsonR1, jsonL1) XCTAssertFalse(83487343.3493 <= jsonR1) - - let jsonL2:JSON = 8773 - let jsonR2:JSON = JSON(-123.23) + + let jsonL2: JSON = 8773 + let jsonR2: JSON = JSON(-123.23) XCTAssertLessThanOrEqual(jsonR2, jsonL2) XCTAssertFalse(9348343 <= jsonR2) - - let jsonL3:JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3:JSON = JSON(NSNumber(value:87621.12345678)) + + let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value:87621.12345678)) XCTAssertLessThanOrEqual(jsonR3, jsonL3) XCTAssertTrue(87621.12345678 <= jsonR3) } func testNumberGreaterThan() { - let jsonL1:JSON = 1234567890.876623 - let jsonR1:JSON = JSON(123.123) + let jsonL1: JSON = 1234567890.876623 + let jsonR1: JSON = JSON(123.123) XCTAssertGreaterThan(jsonL1, jsonR1) XCTAssertFalse(jsonR1 > 192388843.0988) - let jsonL2:JSON = 8773 - let jsonR2:JSON = JSON(123.23) + let jsonL2: JSON = 8773 + let jsonR2: JSON = JSON(123.23) XCTAssertGreaterThan(jsonL2, jsonR2) XCTAssertFalse(jsonR2 > 877434) - let jsonL3:JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3:JSON = JSON(NSNumber(value:87621.1234567)) + let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value:87621.1234567)) XCTAssertGreaterThan(jsonL3, jsonR3) XCTAssertFalse(-7799 > jsonR3) } - + func testNumberLessThan() { - let jsonL1:JSON = 1234567890.876623 - let jsonR1:JSON = JSON(123.123) + let jsonL1: JSON = 1234567890.876623 + let jsonR1: JSON = JSON(123.123) XCTAssertLessThan(jsonR1, jsonL1) XCTAssertTrue(jsonR1 < 192388843.0988) - let jsonL2:JSON = 8773 - let jsonR2:JSON = JSON(123.23) + let jsonL2: JSON = 8773 + let jsonR2: JSON = JSON(123.23) XCTAssertLessThan(jsonR2, jsonL2) XCTAssertTrue(jsonR2 < 877434) - - let jsonL3:JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3:JSON = JSON(NSNumber(value:87621.1234567)) + + let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value:87621.1234567)) XCTAssertLessThan(jsonR3, jsonL3) XCTAssertTrue(-7799 < jsonR3) } func testBoolEqual() { - let jsonL1:JSON = true - let jsonR1:JSON = JSON(true) + let jsonL1: JSON = true + let jsonR1: JSON = JSON(true) XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 == true) - let jsonL2:JSON = false - let jsonR2:JSON = JSON(false) + let jsonL2: JSON = false + let jsonR2: JSON = JSON(false) XCTAssertEqual(jsonL2, jsonR2) XCTAssertTrue(jsonL2 == false) } - + func testBoolNotEqual() { - let jsonL1:JSON = true - let jsonR1:JSON = JSON(false) + let jsonL1: JSON = true + let jsonR1: JSON = JSON(false) XCTAssertNotEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 != false) - let jsonL2:JSON = false - let jsonR2:JSON = JSON(true) + let jsonL2: JSON = false + let jsonR2: JSON = JSON(true) XCTAssertNotEqual(jsonL2, jsonR2) XCTAssertTrue(jsonL2 != true) } - + func testBoolGreaterThanOrEqual() { - let jsonL1:JSON = true - let jsonR1:JSON = JSON(true) + let jsonL1: JSON = true + let jsonR1: JSON = JSON(true) XCTAssertGreaterThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 >= true) - - let jsonL2:JSON = false - let jsonR2:JSON = JSON(false) + + let jsonL2: JSON = false + let jsonR2: JSON = JSON(false) XCTAssertGreaterThanOrEqual(jsonL2, jsonR2) XCTAssertFalse(jsonL2 >= true) } - + func testBoolLessThanOrEqual() { - let jsonL1:JSON = true - let jsonR1:JSON = JSON(true) + let jsonL1: JSON = true + let jsonR1: JSON = JSON(true) XCTAssertLessThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(true <= jsonR1) - - let jsonL2:JSON = false - let jsonR2:JSON = JSON(false) + + let jsonL2: JSON = false + let jsonR2: JSON = JSON(false) XCTAssertLessThanOrEqual(jsonL2, jsonR2) XCTAssertFalse(jsonL2 <= true) } - + func testBoolGreaterThan() { - let jsonL1:JSON = true - let jsonR1:JSON = JSON(true) + let jsonL1: JSON = true + let jsonR1: JSON = JSON(true) XCTAssertFalse(jsonL1 > jsonR1) XCTAssertFalse(jsonL1 > true) XCTAssertFalse(jsonR1 > false) - let jsonL2:JSON = false - let jsonR2:JSON = JSON(false) + let jsonL2: JSON = false + let jsonR2: JSON = JSON(false) XCTAssertFalse(jsonL2 > jsonR2) XCTAssertFalse(jsonL2 > false) XCTAssertFalse(jsonR2 > true) - let jsonL3:JSON = true - let jsonR3:JSON = JSON(false) + let jsonL3: JSON = true + let jsonR3: JSON = JSON(false) XCTAssertFalse(jsonL3 > jsonR3) XCTAssertFalse(jsonL3 > false) XCTAssertFalse(jsonR3 > true) - - let jsonL4:JSON = false - let jsonR4:JSON = JSON(true) + + let jsonL4: JSON = false + let jsonR4: JSON = JSON(true) XCTAssertFalse(jsonL4 > jsonR4) XCTAssertFalse(jsonL4 > false) XCTAssertFalse(jsonR4 > true) } - + func testBoolLessThan() { - let jsonL1:JSON = true - let jsonR1:JSON = JSON(true) + let jsonL1: JSON = true + let jsonR1: JSON = JSON(true) XCTAssertFalse(jsonL1 < jsonR1) XCTAssertFalse(jsonL1 < true) XCTAssertFalse(jsonR1 < false) - let jsonL2:JSON = false - let jsonR2:JSON = JSON(false) + let jsonL2: JSON = false + let jsonR2: JSON = JSON(false) XCTAssertFalse(jsonL2 < jsonR2) XCTAssertFalse(jsonL2 < false) XCTAssertFalse(jsonR2 < true) - - let jsonL3:JSON = true - let jsonR3:JSON = JSON(false) + + let jsonL3: JSON = true + let jsonR3: JSON = JSON(false) XCTAssertFalse(jsonL3 < jsonR3) XCTAssertFalse(jsonL3 < false) XCTAssertFalse(jsonR3 < true) - let jsonL4:JSON = false - let jsonR4:JSON = JSON(true) + let jsonL4: JSON = false + let jsonR4: JSON = JSON(true) XCTAssertFalse(jsonL4 < jsonR4) XCTAssertFalse(jsonL4 < false) XCTAssertFalse(true < jsonR4) } - + func testStringEqual() { - let jsonL1:JSON = "abcdefg 123456789 !@#$%^&*()" - let jsonR1:JSON = JSON("abcdefg 123456789 !@#$%^&*()") + let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" + let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 == "abcdefg 123456789 !@#$%^&*()") } - + func testStringNotEqual() { - let jsonL1:JSON = "abcdefg 123456789 !@#$%^&*()" - let jsonR1:JSON = JSON("-=[]\\\"987654321") - + let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" + let jsonR1: JSON = JSON("-=[]\\\"987654321") + XCTAssertNotEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 != "not equal") } - + func testStringGreaterThanOrEqual() { - let jsonL1:JSON = "abcdefg 123456789 !@#$%^&*()" - let jsonR1:JSON = JSON("abcdefg 123456789 !@#$%^&*()") - + let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" + let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") + XCTAssertGreaterThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 >= "abcdefg 123456789 !@#$%^&*()") - let jsonL2:JSON = "z-+{}:" - let jsonR2:JSON = JSON("a<>?:") + let jsonL2: JSON = "z-+{}:" + let jsonR2: JSON = JSON("a<>?:") XCTAssertGreaterThanOrEqual(jsonL2, jsonR2) XCTAssertTrue(jsonL2 >= "mnbvcxz") } - + func testStringLessThanOrEqual() { - let jsonL1:JSON = "abcdefg 123456789 !@#$%^&*()" - let jsonR1:JSON = JSON("abcdefg 123456789 !@#$%^&*()") - + let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" + let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") + XCTAssertLessThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 <= "abcdefg 123456789 !@#$%^&*()") - - let jsonL2:JSON = "z-+{}:" - let jsonR2:JSON = JSON("a<>?:") + + let jsonL2: JSON = "z-+{}:" + let jsonR2: JSON = JSON("a<>?:") XCTAssertLessThanOrEqual(jsonR2, jsonL2) XCTAssertTrue("mnbvcxz" <= jsonL2) } - + func testStringGreaterThan() { - let jsonL1:JSON = "abcdefg 123456789 !@#$%^&*()" - let jsonR1:JSON = JSON("abcdefg 123456789 !@#$%^&*()") - + let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" + let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") + XCTAssertFalse(jsonL1 > jsonR1) XCTAssertFalse(jsonL1 > "abcdefg 123456789 !@#$%^&*()") - - let jsonL2:JSON = "z-+{}:" - let jsonR2:JSON = JSON("a<>?:") + + let jsonL2: JSON = "z-+{}:" + let jsonR2: JSON = JSON("a<>?:") XCTAssertGreaterThan(jsonL2, jsonR2) XCTAssertFalse("87663434" > jsonL2) } func testStringLessThan() { - let jsonL1:JSON = "abcdefg 123456789 !@#$%^&*()" - let jsonR1:JSON = JSON("abcdefg 123456789 !@#$%^&*()") - + let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" + let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") + XCTAssertFalse(jsonL1 < jsonR1) XCTAssertFalse(jsonL1 < "abcdefg 123456789 !@#$%^&*()") - - let jsonL2:JSON = "98774" - let jsonR2:JSON = JSON("123456") + + let jsonL2: JSON = "98774" + let jsonR2: JSON = JSON("123456") XCTAssertLessThan(jsonR2, jsonL2) XCTAssertFalse(jsonL2 < "09") } func testNil() { - let jsonL1:JSON = JSON.null - let jsonR1:JSON = JSON(NSNull()) + let jsonL1: JSON = JSON.null + let jsonR1: JSON = JSON(NSNull()) XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 != "123") XCTAssertFalse(jsonL1 > "abcd") @@ -308,31 +307,31 @@ class ComparableTests: XCTestCase { XCTAssertTrue(jsonL1 >= jsonR1) XCTAssertTrue(jsonL1 <= jsonR1) } - + func testArray() { - let jsonL1:JSON = [1,2,"4",5,"6"] - let jsonR1:JSON = JSON([1,2,"4",5,"6"]) + let jsonL1: JSON = [1, 2, "4", 5, "6"] + let jsonR1: JSON = JSON([1, 2, "4", 5, "6"]) XCTAssertEqual(jsonL1, jsonR1) - XCTAssertTrue(jsonL1 == [1,2,"4",5,"6"]) - XCTAssertTrue(jsonL1 != ["abcd","efg"]) + XCTAssertTrue(jsonL1 == [1, 2, "4", 5, "6"]) + XCTAssertTrue(jsonL1 != ["abcd", "efg"]) XCTAssertTrue(jsonL1 >= jsonR1) XCTAssertTrue(jsonL1 <= jsonR1) - XCTAssertFalse(jsonL1 > ["abcd",""]) + XCTAssertFalse(jsonL1 > ["abcd", ""]) XCTAssertFalse(jsonR1 < []) XCTAssertFalse(jsonL1 >= [:]) } - + func testDictionary() { - let jsonL1:JSON = ["2": 2, "name": "Jack", "List": ["a", 1.09, NSNull()]] - let jsonR1:JSON = JSON(["2": 2, "name": "Jack", "List": ["a", 1.09, NSNull()]]) - + let jsonL1: JSON = ["2": 2, "name": "Jack", "List": ["a", 1.09, NSNull()]] + let jsonR1: JSON = JSON(["2": 2, "name": "Jack", "List": ["a", 1.09, NSNull()]]) + XCTAssertEqual(jsonL1, jsonR1) - XCTAssertTrue(jsonL1 != ["1":2,"Hello":"World","Koo":"Foo"]) + XCTAssertTrue(jsonL1 != ["1": 2, "Hello": "World", "Koo": "Foo"]) XCTAssertTrue(jsonL1 >= jsonR1) XCTAssertTrue(jsonL1 <= jsonR1) XCTAssertFalse(jsonL1 >= [:]) - XCTAssertFalse(jsonR1 <= ["999":"aaaa"]) - XCTAssertFalse(jsonL1 > [")(*&^":1234567]) - XCTAssertFalse(jsonR1 < ["MNHH":"JUYTR"]) + XCTAssertFalse(jsonR1 <= ["999": "aaaa"]) + XCTAssertFalse(jsonL1 > [")(*&^": 1234567]) + XCTAssertFalse(jsonR1 < ["MNHH": "JUYTR"]) } } diff --git a/Tests/SwiftyJSONTests/DictionaryTests.swift b/Tests/SwiftyJSONTests/DictionaryTests.swift index 5f9c822f..5d73f23b 100644 --- a/Tests/SwiftyJSONTests/DictionaryTests.swift +++ b/Tests/SwiftyJSONTests/DictionaryTests.swift @@ -26,7 +26,7 @@ import SwiftyJSON class DictionaryTests: XCTestCase { func testGetter() { - let dictionary = ["number":9823.212, "name":"NAME", "list":[1234, 4.212], "object":["sub_number":877.2323, "sub_name":"sub_name"], "bool":true] as [String : Any] + let dictionary = ["number": 9823.212, "name": "NAME", "list": [1234, 4.212], "object": ["sub_number": 877.2323, "sub_name": "sub_name"], "bool": true] as [String : Any] let json = JSON(dictionary) //dictionary XCTAssertEqual((json.dictionary!["number"]! as JSON).double!, 9823.212) @@ -45,11 +45,11 @@ class DictionaryTests: XCTestCase { XCTAssertTrue(json.dictionaryObject!["null"] == nil) XCTAssertTrue(JSON.null.dictionaryObject == nil) } - + func testSetter() { - var json:JSON = ["test":"case"] - XCTAssertEqual(json.dictionaryObject! as! [String : String], ["test":"case"]) - json.dictionaryObject = ["name":"NAME"] - XCTAssertEqual(json.dictionaryObject! as! [String : String], ["name":"NAME"]) + var json: JSON = ["test": "case"] + XCTAssertEqual(json.dictionaryObject! as! [String : String], ["test": "case"]) + json.dictionaryObject = ["name": "NAME"] + XCTAssertEqual(json.dictionaryObject! as! [String : String], ["name": "NAME"]) } } diff --git a/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift b/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift index fa88e231..9e478c7b 100644 --- a/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift +++ b/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift @@ -26,7 +26,7 @@ import SwiftyJSON class LiteralConvertibleTests: XCTestCase { func testNumber() { - var json:JSON = 1234567890.876623 + var json: JSON = 1234567890.876623 XCTAssertEqual(json.int!, 1234567890) XCTAssertEqual(json.intValue, 1234567890) XCTAssertEqual(json.double!, 1234567890.876623) @@ -34,40 +34,40 @@ class LiteralConvertibleTests: XCTestCase { XCTAssertTrue(json.float! == 1234567890.876623) XCTAssertTrue(json.floatValue == 1234567890.876623) } - + func testBool() { - var jsonTrue:JSON = true + var jsonTrue: JSON = true XCTAssertEqual(jsonTrue.bool!, true) XCTAssertEqual(jsonTrue.boolValue, true) - var jsonFalse:JSON = false + var jsonFalse: JSON = false XCTAssertEqual(jsonFalse.bool!, false) XCTAssertEqual(jsonFalse.boolValue, false) } func testString() { - var json:JSON = "abcd efg, HIJK;LMn" + var json: JSON = "abcd efg, HIJK;LMn" XCTAssertEqual(json.string!, "abcd efg, HIJK;LMn") XCTAssertEqual(json.stringValue, "abcd efg, HIJK;LMn") } - + func testNil() { - let jsonNil_1:JSON = JSON.null + let jsonNil_1: JSON = JSON.null XCTAssert(jsonNil_1 == JSON.null) - let jsonNil_2:JSON = JSON(NSNull.self) + let jsonNil_2: JSON = JSON(NSNull.self) XCTAssert(jsonNil_2 != JSON.null) - let jsonNil_3:JSON = JSON([1:2]) + let jsonNil_3: JSON = JSON([1: 2]) XCTAssert(jsonNil_3 != JSON.null) } - + func testArray() { - let json:JSON = [1,2,"4",5,"6"] - XCTAssertEqual(json.array!, [1,2,"4",5,"6"]) - XCTAssertEqual(json.arrayValue, [1,2,"4",5,"6"]) + let json: JSON = [1, 2, "4", 5, "6"] + XCTAssertEqual(json.array!, [1, 2, "4", 5, "6"]) + XCTAssertEqual(json.arrayValue, [1, 2, "4", 5, "6"]) } - + func testDictionary() { - let json:JSON = ["1":2,"2":2,"three":3,"list":["aa","bb","dd"]] - XCTAssertEqual(json.dictionary!, ["1":2,"2":2,"three":3,"list":["aa","bb","dd"]]) - XCTAssertEqual(json.dictionaryValue, ["1":2,"2":2,"three":3,"list":["aa","bb","dd"]]) + let json: JSON = ["1": 2, "2": 2, "three": 3, "list": ["aa", "bb", "dd"]] + XCTAssertEqual(json.dictionary!, ["1": 2, "2": 2, "three": 3, "list": ["aa", "bb", "dd"]]) + XCTAssertEqual(json.dictionaryValue, ["1": 2, "2": 2, "three": 3, "list": ["aa", "bb", "dd"]]) } } diff --git a/Tests/SwiftyJSONTests/MergeTests.swift b/Tests/SwiftyJSONTests/MergeTests.swift index ddc4a24f..dbee6a35 100644 --- a/Tests/SwiftyJSONTests/MergeTests.swift +++ b/Tests/SwiftyJSONTests/MergeTests.swift @@ -25,11 +25,11 @@ import XCTest import SwiftyJSON class JSONTests: XCTestCase { - + func testDifferingTypes() { let A = JSON("a") let B = JSON(1) - + do { _ = try A.merged(with: B) XCTFail() @@ -41,61 +41,61 @@ class JSONTests: XCTestCase { "Couldn't merge, because the JSONs differ in type on top level.") } } - + func testPrimitiveType() { let A = JSON("a") let B = JSON("b") XCTAssertEqual(try! A.merged(with: B), B) } - + func testMergeEqual() { let json = JSON(["a": "A"]) XCTAssertEqual(try! json.merged(with: json), json) } - + func testMergeUnequalValues() { let A = JSON(["a": "A"]) let B = JSON(["a": "B"]) XCTAssertEqual(try! A.merged(with: B), B) } - + func testMergeUnequalKeysAndValues() { let A = JSON(["a": "A"]) let B = JSON(["b": "B"]) XCTAssertEqual(try! A.merged(with: B), JSON(["a": "A", "b": "B"])) } - + func testMergeFilledAndEmpty() { let A = JSON(["a": "A"]) let B = JSON([:]) XCTAssertEqual(try! A.merged(with: B), A) } - + func testMergeEmptyAndFilled() { let A = JSON([:]) let B = JSON(["a": "A"]) XCTAssertEqual(try! A.merged(with: B), B) } - + func testMergeArray() { let A = JSON(["a"]) let B = JSON(["b"]) XCTAssertEqual(try! A.merged(with: B), JSON(["a", "b"])) } - + func testMergeNestedJSONs() { let A = JSON([ "nested": [ "A": "a" ] ]) - + let B = JSON([ "nested": [ "A": "b" ] ]) - + XCTAssertEqual(try! A.merged(with: B), B) } } diff --git a/Tests/SwiftyJSONTests/NestedJSONTests.swift b/Tests/SwiftyJSONTests/NestedJSONTests.swift index 5c75def7..7134eeca 100644 --- a/Tests/SwiftyJSONTests/NestedJSONTests.swift +++ b/Tests/SwiftyJSONTests/NestedJSONTests.swift @@ -11,28 +11,28 @@ import SwiftyJSON class NestedJSONTests: XCTestCase { let family: JSON = [ - "names" : [ + "names": [ "Brooke Abigail Matos", "Rowan Danger Matos" ], - "motto" : "Hey, I don't know about you, but I'm feeling twenty-two! So, release the KrakenDev!" + "motto": "Hey, I don't know about you, but I'm feeling twenty-two! So, release the KrakenDev!" ] - + func testTopLevelNestedJSON() { let nestedJSON: JSON = [ - "family" : family + "family": family ] XCTAssertNotNil(try? nestedJSON.rawData()) } - + func testDeeplyNestedJSON() { let nestedFamily: JSON = [ "count": 1, "families": [ [ - "isACoolFamily" : true, - "family" : [ - "hello" : family + "isACoolFamily": true, + "family": [ + "hello": family ] ] ] diff --git a/Tests/SwiftyJSONTests/NumberTests.swift b/Tests/SwiftyJSONTests/NumberTests.swift index 0ae66b54..6b0c8aa9 100644 --- a/Tests/SwiftyJSONTests/NumberTests.swift +++ b/Tests/SwiftyJSONTests/NumberTests.swift @@ -31,68 +31,68 @@ class NumberTests: XCTestCase { XCTAssertEqual(json.number!, 9876543210.123456789) XCTAssertEqual(json.numberValue, 9876543210.123456789) XCTAssertEqual(json.stringValue, "9876543210.123457") - + json.string = "1000000000000000000000000000.1" XCTAssertNil(json.number) XCTAssertEqual(json.numberValue.description, "1000000000000000000000000000.1") json.string = "1e+27" XCTAssertEqual(json.numberValue.description, "1000000000000000000000000000") - + //setter json.number = NSNumber(value: 123456789.0987654321) XCTAssertEqual(json.number!, 123456789.0987654321) XCTAssertEqual(json.numberValue, 123456789.0987654321) - + json.number = nil XCTAssertEqual(json.numberValue, 0) XCTAssertEqual(json.object as? NSNull, NSNull()) XCTAssertTrue(json.number == nil) - + json.numberValue = 2.9876 XCTAssertEqual(json.number!, 2.9876) } - + func testBool() { var json = JSON(true) XCTAssertEqual(json.bool!, true) XCTAssertEqual(json.boolValue, true) XCTAssertEqual(json.numberValue, true as NSNumber) XCTAssertEqual(json.stringValue, "true") - + json.bool = false XCTAssertEqual(json.bool!, false) XCTAssertEqual(json.boolValue, false) XCTAssertEqual(json.numberValue, false as NSNumber) - + json.bool = nil XCTAssertTrue(json.bool == nil) XCTAssertEqual(json.boolValue, false) XCTAssertEqual(json.numberValue, 0) - + json.boolValue = true XCTAssertEqual(json.bool!, true) XCTAssertEqual(json.boolValue, true) XCTAssertEqual(json.numberValue, true as NSNumber) } - + func testDouble() { var json = JSON(9876543210.123456789) XCTAssertEqual(json.double!, 9876543210.123456789) XCTAssertEqual(json.doubleValue, 9876543210.123456789) XCTAssertEqual(json.numberValue, 9876543210.123456789) XCTAssertEqual(json.stringValue, "9876543210.123457") - + json.double = 2.8765432 XCTAssertEqual(json.double!, 2.8765432) XCTAssertEqual(json.doubleValue, 2.8765432) XCTAssertEqual(json.numberValue, 2.8765432) - + json.doubleValue = 89.0987654 XCTAssertEqual(json.double!, 89.0987654) XCTAssertEqual(json.doubleValue, 89.0987654) XCTAssertEqual(json.numberValue, 89.0987654) - + json.double = nil XCTAssertEqual(json.boolValue, false) XCTAssertEqual(json.doubleValue, 0.0) @@ -106,68 +106,68 @@ class NumberTests: XCTestCase { print(json.numberValue.doubleValue) XCTAssertEqual(json.numberValue, 54321.12345) XCTAssertEqual(json.stringValue, "54321.12345") - + json.double = 23231.65 XCTAssertTrue(json.float! == 23231.65) XCTAssertTrue(json.floatValue == 23231.65) XCTAssertEqual(json.numberValue, NSNumber(value:23231.65)) - + json.double = -98766.23 XCTAssertEqual(json.float!, -98766.23) XCTAssertEqual(json.floatValue, -98766.23) XCTAssertEqual(json.numberValue, NSNumber(value:-98766.23)) } - + func testInt() { var json = JSON(123456789) XCTAssertEqual(json.int!, 123456789) XCTAssertEqual(json.intValue, 123456789) XCTAssertEqual(json.numberValue, NSNumber(value: 123456789)) XCTAssertEqual(json.stringValue, "123456789") - + json.int = nil XCTAssertTrue(json.boolValue == false) XCTAssertTrue(json.intValue == 0) XCTAssertEqual(json.numberValue, 0) XCTAssertEqual(json.object as? NSNull, NSNull()) XCTAssertTrue(json.int == nil) - + json.intValue = 76543 XCTAssertEqual(json.int!, 76543) XCTAssertEqual(json.intValue, 76543) XCTAssertEqual(json.numberValue, NSNumber(value: 76543)) - + json.intValue = 98765421 XCTAssertEqual(json.int!, 98765421) XCTAssertEqual(json.intValue, 98765421) XCTAssertEqual(json.numberValue, NSNumber(value: 98765421)) } - + func testUInt() { var json = JSON(123456789) XCTAssertTrue(json.uInt! == 123456789) XCTAssertTrue(json.uIntValue == 123456789) XCTAssertEqual(json.numberValue, NSNumber(value: 123456789)) XCTAssertEqual(json.stringValue, "123456789") - + json.uInt = nil XCTAssertTrue(json.boolValue == false) XCTAssertTrue(json.uIntValue == 0) XCTAssertEqual(json.numberValue, 0) XCTAssertEqual(json.object as? NSNull, NSNull()) XCTAssertTrue(json.uInt == nil) - + json.uIntValue = 76543 XCTAssertTrue(json.uInt! == 76543) XCTAssertTrue(json.uIntValue == 76543) XCTAssertEqual(json.numberValue, NSNumber(value: 76543)) - + json.uIntValue = 98765421 XCTAssertTrue(json.uInt! == 98765421) XCTAssertTrue(json.uIntValue == 98765421) XCTAssertEqual(json.numberValue, NSNumber(value: 98765421)) } - + func testInt8() { let n127 = NSNumber(value: 127) var json = JSON(n127) @@ -176,7 +176,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == n127) XCTAssertEqual(json.numberValue, n127) XCTAssertEqual(json.stringValue, "127") - + let nm128 = NSNumber(value: -128) json.int8Value = nm128.int8Value XCTAssertTrue(json.int8! == nm128.int8Value) @@ -184,7 +184,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == nm128) XCTAssertEqual(json.numberValue, nm128) XCTAssertEqual(json.stringValue, "-128") - + let n0 = NSNumber(value: 0 as Int8) json.int8Value = n0.int8Value XCTAssertTrue(json.int8! == n0.int8Value) @@ -192,8 +192,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") - - + let n1 = NSNumber(value: 1 as Int8) json.int8Value = n1.int8Value XCTAssertTrue(json.int8! == n1.int8Value) @@ -202,7 +201,7 @@ class NumberTests: XCTestCase { XCTAssertEqual(json.numberValue, n1) XCTAssertEqual(json.stringValue, "1") } - + func testUInt8() { let n255 = NSNumber(value: 255) var json = JSON(n255) @@ -211,7 +210,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == n255) XCTAssertEqual(json.numberValue, n255) XCTAssertEqual(json.stringValue, "255") - + let nm2 = NSNumber(value: 2) json.uInt8Value = nm2.uint8Value XCTAssertTrue(json.uInt8! == nm2.uint8Value) @@ -219,7 +218,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == nm2) XCTAssertEqual(json.numberValue, nm2) XCTAssertEqual(json.stringValue, "2") - + let nm0 = NSNumber(value: 0) json.uInt8Value = nm0.uint8Value XCTAssertTrue(json.uInt8! == nm0.uint8Value) @@ -238,7 +237,7 @@ class NumberTests: XCTestCase { } func testInt16() { - + let n32767 = NSNumber(value: 32767) var json = JSON(n32767) XCTAssertTrue(json.int16! == n32767.int16Value) @@ -246,7 +245,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") - + let nm32768 = NSNumber(value: -32768) json.int16Value = nm32768.int16Value XCTAssertTrue(json.int16! == nm32768.int16Value) @@ -254,7 +253,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == nm32768) XCTAssertEqual(json.numberValue, nm32768) XCTAssertEqual(json.stringValue, "-32768") - + let n0 = NSNumber(value: 0) json.int16Value = n0.int16Value XCTAssertTrue(json.int16! == n0.int16Value) @@ -262,7 +261,7 @@ class NumberTests: XCTestCase { XCTAssertEqual(json.number, n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") - + let n1 = NSNumber(value: 1) json.int16 = n1.int16Value XCTAssertTrue(json.int16! == n1.int16Value) @@ -299,7 +298,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == n2147483647) XCTAssertEqual(json.numberValue, n2147483647) XCTAssertEqual(json.stringValue, "2147483647") - + let n32767 = NSNumber(value: 32767) json.int32 = n32767.int32Value XCTAssertTrue(json.int32! == n32767.int32Value) @@ -307,7 +306,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") - + let nm2147483648 = NSNumber(value: -2147483648) json.int32Value = nm2147483648.int32Value XCTAssertTrue(json.int32! == nm2147483648.int32Value) @@ -316,7 +315,7 @@ class NumberTests: XCTestCase { XCTAssertEqual(json.numberValue, nm2147483648) XCTAssertEqual(json.stringValue, "-2147483648") } - + func testUInt32() { let n2147483648 = NSNumber(value: 2147483648 as UInt32) var json = JSON(n2147483648) @@ -325,7 +324,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == n2147483648) XCTAssertEqual(json.numberValue, n2147483648) XCTAssertEqual(json.stringValue, "2147483648") - + let n32767 = NSNumber(value: 32767 as UInt32) json.uInt32 = n32767.uint32Value XCTAssertTrue(json.uInt32! == n32767.uint32Value) @@ -333,7 +332,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") - + let n0 = NSNumber(value: 0 as UInt32) json.uInt32Value = n0.uint32Value XCTAssertTrue(json.uInt32! == n0.uint32Value) @@ -351,7 +350,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == int64Max) XCTAssertEqual(json.numberValue, int64Max) XCTAssertEqual(json.stringValue, int64Max.stringValue) - + let n32767 = NSNumber(value: 32767) json.int64 = n32767.int64Value XCTAssertTrue(json.int64! == n32767.int64Value) @@ -359,7 +358,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") - + let int64Min = NSNumber(value: (INT64_MAX-1) * -1) json.int64Value = int64Min.int64Value XCTAssertTrue(json.int64! == int64Min.int64Value) @@ -368,7 +367,7 @@ class NumberTests: XCTestCase { XCTAssertEqual(json.numberValue, int64Min) XCTAssertEqual(json.stringValue, int64Min.stringValue) } - + func testUInt64() { let uInt64Max = NSNumber(value: UINT64_MAX) var json = JSON(uInt64Max) @@ -377,7 +376,7 @@ class NumberTests: XCTestCase { XCTAssertTrue(json.number! == uInt64Max) XCTAssertEqual(json.numberValue, uInt64Max) XCTAssertEqual(json.stringValue, uInt64Max.stringValue) - + let n32767 = NSNumber(value: 32767) json.int64 = n32767.int64Value XCTAssertTrue(json.int64! == n32767.int64Value) diff --git a/Tests/SwiftyJSONTests/PerformanceTests.swift b/Tests/SwiftyJSONTests/PerformanceTests.swift index e3ed9760..850d3e90 100644 --- a/Tests/SwiftyJSONTests/PerformanceTests.swift +++ b/Tests/SwiftyJSONTests/PerformanceTests.swift @@ -26,34 +26,34 @@ import SwiftyJSON class PerformanceTests: XCTestCase { var testData: Data! - + override func setUp() { super.setUp() - + if let file = Bundle(for:PerformanceTests.self).path(forResource: "Tests", ofType: "json") { self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { XCTFail("Can't find the test JSON file") } } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } - + func testInitPerformance() { - self.measure() { + self.measure { for _ in 1...100 { let json = JSON(data:self.testData) XCTAssertTrue(json != JSON.null) } } } - + func testObjectMethodPerformance() { let json = JSON(data:self.testData) - self.measure() { + self.measure { for _ in 1...100 { let object:Any? = json.object XCTAssertTrue(object != nil) @@ -63,9 +63,9 @@ class PerformanceTests: XCTestCase { func testArrayMethodPerformance() { let json = JSON(data:self.testData) - self.measure() { + self.measure { for _ in 1...100 { - autoreleasepool{ + autoreleasepool { if let array = json.array { XCTAssertTrue(array.count > 0) } @@ -73,12 +73,12 @@ class PerformanceTests: XCTestCase { } } } - + func testDictionaryMethodPerformance() { let json = JSON(data:testData)[0] - self.measure() { + self.measure { for _ in 1...100 { - autoreleasepool{ + autoreleasepool { if let dictionary = json.dictionary { XCTAssertTrue(dictionary.count > 0) } @@ -86,12 +86,12 @@ class PerformanceTests: XCTestCase { } } } - + func testRawStringMethodPerformance() { let json = JSON(data:testData) - self.measure() { + self.measure { for _ in 1...100 { - autoreleasepool{ + autoreleasepool { let string = json.rawString() XCTAssertTrue(string != nil) } @@ -108,9 +108,9 @@ class PerformanceTests: XCTestCase { ]) } let json = JSON(data) - - self.measure() { - autoreleasepool{ + + self.measure { + autoreleasepool { if let dictionary = json.dictionary { XCTAssertTrue(dictionary.count > 0) } else { diff --git a/Tests/SwiftyJSONTests/PrintableTests.swift b/Tests/SwiftyJSONTests/PrintableTests.swift index f60fc8c1..ebecbe1a 100644 --- a/Tests/SwiftyJSONTests/PrintableTests.swift +++ b/Tests/SwiftyJSONTests/PrintableTests.swift @@ -25,37 +25,37 @@ import SwiftyJSON class PrintableTests: XCTestCase { func testNumber() { - let json:JSON = 1234567890.876623 + let json: JSON = 1234567890.876623 XCTAssertEqual(json.description, "1234567890.876623") XCTAssertEqual(json.debugDescription, "1234567890.876623") } - + func testBool() { - let jsonTrue:JSON = true + let jsonTrue: JSON = true XCTAssertEqual(jsonTrue.description, "true") XCTAssertEqual(jsonTrue.debugDescription, "true") - let jsonFalse:JSON = false + let jsonFalse: JSON = false XCTAssertEqual(jsonFalse.description, "false") XCTAssertEqual(jsonFalse.debugDescription, "false") } - + func testString() { - let json:JSON = "abcd efg, HIJK;LMn" + let json: JSON = "abcd efg, HIJK;LMn" XCTAssertEqual(json.description, "abcd efg, HIJK;LMn") XCTAssertEqual(json.debugDescription, "abcd efg, HIJK;LMn") } - + func testNil() { - let jsonNil_1:JSON = JSON.null + let jsonNil_1: JSON = JSON.null XCTAssertEqual(jsonNil_1.description, "null") XCTAssertEqual(jsonNil_1.debugDescription, "null") - let jsonNil_2:JSON = JSON(NSNull()) + let jsonNil_2: JSON = JSON(NSNull()) XCTAssertEqual(jsonNil_2.description, "null") XCTAssertEqual(jsonNil_2.debugDescription, "null") } - + func testArray() { - let json:JSON = [1,2,"4",5,"6"] + let json: JSON = [1, 2, "4", 5, "6"] var description = json.description.replacingOccurrences(of: "\n", with: "") description = description.replacingOccurrences(of: " ", with: "") XCTAssertEqual(description, "[1,2,\"4\",5,\"6\"]") @@ -74,7 +74,7 @@ class PrintableTests: XCTestCase { } func testArrayWithOptionals() { - let array = [1,2,"4",5,"6",nil] as [Any?] + let array = [1, 2, "4", 5, "6", nil] as [Any?] let json = JSON(array) guard var description = json.rawString([.castNilToNSNull: true]) else { XCTFail("could not represent array") @@ -86,9 +86,9 @@ class PrintableTests: XCTestCase { XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0) } - + func testDictionary() { - let json:JSON = ["1":2,"2":"two", "3":3] + let json: JSON = ["1": 2, "2": "two", "3": 3] var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) @@ -98,7 +98,7 @@ class PrintableTests: XCTestCase { } func testDictionaryWithStrings() { - let dict = ["foo":"{\"bar\":123}"] as [String : Any] + let dict = ["foo": "{\"bar\":123}"] as [String : Any] let json = JSON(dict) var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") @@ -108,7 +108,7 @@ class PrintableTests: XCTestCase { } func testDictionaryWithOptionals() { - let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] + let dict = ["1": 2, "2": "two", "3": nil] as [String: Any?] let json = JSON(dict) guard var description = json.rawString([.castNilToNSNull: true]) else { XCTFail("could not represent dictionary") diff --git a/Tests/SwiftyJSONTests/RawRepresentableTests.swift b/Tests/SwiftyJSONTests/RawRepresentableTests.swift index 9ebf9b2e..1482a05b 100644 --- a/Tests/SwiftyJSONTests/RawRepresentableTests.swift +++ b/Tests/SwiftyJSONTests/RawRepresentableTests.swift @@ -26,40 +26,40 @@ import SwiftyJSON class RawRepresentableTests: XCTestCase { func testNumber() { - var json:JSON = JSON(rawValue: 948394394.347384 as NSNumber)! + var json: JSON = JSON(rawValue: 948394394.347384 as NSNumber)! XCTAssertEqual(json.int!, 948394394) XCTAssertEqual(json.intValue, 948394394) XCTAssertEqual(json.double!, 948394394.347384) XCTAssertEqual(json.doubleValue, 948394394.347384) XCTAssertTrue(json.float! == 948394394.347384) XCTAssertTrue(json.floatValue == 948394394.347384) - + let object: Any = json.rawValue XCTAssertEqual(object as? Int, 948394394) XCTAssertEqual(object as? Double, 948394394.347384) XCTAssertTrue(object as! Float == 948394394.347384) XCTAssertEqual(object as? NSNumber, 948394394.347384) } - + func testBool() { - var jsonTrue:JSON = JSON(rawValue: true as NSNumber)! + var jsonTrue: JSON = JSON(rawValue: true as NSNumber)! XCTAssertEqual(jsonTrue.bool!, true) XCTAssertEqual(jsonTrue.boolValue, true) - - var jsonFalse:JSON = JSON(rawValue: false)! + + var jsonFalse: JSON = JSON(rawValue: false)! XCTAssertEqual(jsonFalse.bool!, false) XCTAssertEqual(jsonFalse.boolValue, false) - + let objectTrue = jsonTrue.rawValue XCTAssertEqual(objectTrue as? Bool, true) - + let objectFalse = jsonFalse.rawValue XCTAssertEqual(objectFalse as? Bool, false) } - + func testString() { let string = "The better way to deal with JSON data in Swift." - if let json:JSON = JSON(rawValue: string) { + if let json: JSON = JSON(rawValue: string) { XCTAssertEqual(json.string!, string) XCTAssertEqual(json.stringValue, string) XCTAssertTrue(json.array == nil) @@ -71,30 +71,30 @@ class RawRepresentableTests: XCTestCase { } else { XCTFail("Should not run into here") } - + let object: Any = JSON(rawValue: string)!.rawValue XCTAssertEqual(object as? String, string) } - + func testNil() { if let _ = JSON(rawValue: NSObject()) { XCTFail("Should not run into here") } } - + func testArray() { - let array = [1,2,"3",4102,"5632", "abocde", "!@# $%^&*()"] as NSArray - if let json:JSON = JSON(rawValue: array) { + let array = [1, 2, "3", 4102, "5632", "abocde", "!@# $%^&*()"] as NSArray + if let json: JSON = JSON(rawValue: array) { XCTAssertEqual(json, JSON(array)) } - + let object: Any = JSON(rawValue: array)!.rawValue XCTAssertTrue(array == object as! NSArray) } - + func testDictionary() { - let dictionary = ["1":2,"2":2,"three":3,"list":["aa","bb","dd"]] as NSDictionary - if let json:JSON = JSON(rawValue: dictionary) { + let dictionary = ["1": 2, "2": 2, "three": 3, "list": ["aa", "bb", "dd"]] as NSDictionary + if let json: JSON = JSON(rawValue: dictionary) { XCTAssertEqual(json, JSON(dictionary)) } diff --git a/Tests/SwiftyJSONTests/RawTests.swift b/Tests/SwiftyJSONTests/RawTests.swift index 7693d8e3..faa043a1 100644 --- a/Tests/SwiftyJSONTests/RawTests.swift +++ b/Tests/SwiftyJSONTests/RawTests.swift @@ -26,7 +26,7 @@ import SwiftyJSON class RawTests: XCTestCase { func testRawData() { - let json: JSON = ["somekey" : "some string value"] + let json: JSON = ["somekey": "some string value"] let expectedRawData = "{\"somekey\":\"some string value\"}".data(using: String.Encoding.utf8) do { let data: Data = try json.rawData() @@ -35,7 +35,7 @@ class RawTests: XCTestCase { XCTFail() } } - + func testInvalidJSONForRawData() { let json: JSON = "...xyz" do { @@ -44,9 +44,9 @@ class RawTests: XCTestCase { XCTAssertEqual(error.code, ErrorInvalidJSON) } } - + func testArray() { - let json:JSON = [1, "2", 3.12, NSNull(), true, ["name": "Jack"]] + let json: JSON = [1, "2", 3.12, NSNull(), true, ["name": "Jack"]] let data: Data? do { data = try json.rawData() @@ -58,9 +58,9 @@ class RawTests: XCTestCase { XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0) print(string!) } - + func testDictionary() { - let json:JSON = ["number":111111.23456789, "name":"Jack", "list":[1,2,3,4], "bool":false, "null":NSNull()] + let json: JSON = ["number": 111111.23456789, "name": "Jack", "list": [1, 2, 3, 4], "bool": false, "null": NSNull()] let data: Data? do { data = try json.rawData() @@ -72,24 +72,24 @@ class RawTests: XCTestCase { XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0) print(string!) } - + func testString() { - let json:JSON = "I'm a json" + let json: JSON = "I'm a json" XCTAssertEqual(json.rawString(), "I'm a json") } - + func testNumber() { - let json:JSON = 123456789.123 + let json: JSON = 123456789.123 XCTAssertEqual(json.rawString(), "123456789.123") } - + func testBool() { - let json:JSON = true + let json: JSON = true XCTAssertEqual(json.rawString(), "true") } - + func testNull() { - let json:JSON = JSON.null + let json: JSON = JSON.null XCTAssertEqual(json.rawString(), "null") } } diff --git a/Tests/SwiftyJSONTests/SequenceTypeTests.swift b/Tests/SwiftyJSONTests/SequenceTypeTests.swift index 8f164c4c..3c388b7e 100644 --- a/Tests/SwiftyJSONTests/SequenceTypeTests.swift +++ b/Tests/SwiftyJSONTests/SequenceTypeTests.swift @@ -48,7 +48,7 @@ class SequenceTypeTests: XCTestCase { } func testArrayAllNumber() { - var json:JSON = [1,2.0,3.3,123456789,987654321.123456789] + var json: JSON = [1, 2.0, 3.3, 123456789, 987654321.123456789] XCTAssertEqual(json.count, 5) var index = 0 @@ -60,11 +60,11 @@ class SequenceTypeTests: XCTestCase { index += 1 } XCTAssertEqual(index, 5) - XCTAssertEqual(array, [1,2.0,3.3,123456789,987654321.123456789]) + XCTAssertEqual(array, [1, 2.0, 3.3, 123456789, 987654321.123456789]) } func testArrayAllBool() { - var json:JSON = JSON([true, false, false, true, true]) + var json: JSON = JSON([true, false, false, true, true]) XCTAssertEqual(json.count, 5) var index = 0 @@ -80,7 +80,7 @@ class SequenceTypeTests: XCTestCase { } func testArrayAllString() { - var json:JSON = JSON(rawValue: ["aoo","bpp","zoo"] as NSArray)! + var json: JSON = JSON(rawValue: ["aoo", "bpp", "zoo"] as NSArray)! XCTAssertEqual(json.count, 3) var index = 0 @@ -92,11 +92,11 @@ class SequenceTypeTests: XCTestCase { index += 1 } XCTAssertEqual(index, 3) - XCTAssertEqual(array, ["aoo","bpp","zoo"]) + XCTAssertEqual(array, ["aoo", "bpp", "zoo"]) } func testArrayWithNull() { - var json:JSON = JSON(rawValue: ["aoo","bpp", NSNull() ,"zoo"] as NSArray)! + var json: JSON = JSON(rawValue: ["aoo", "bpp", NSNull(), "zoo"] as NSArray)! XCTAssertEqual(json.count, 4) var index = 0 @@ -113,7 +113,7 @@ class SequenceTypeTests: XCTestCase { } func testArrayAllDictionary() { - var json:JSON = [["1":1, "2":2], ["a":"A", "b":"B"], ["null":NSNull()]] + var json: JSON = [["1": 1, "2": 2], ["a": "A", "b": "B"], ["null": NSNull()]] XCTAssertEqual(json.count, 3) var index = 0 @@ -133,11 +133,11 @@ class SequenceTypeTests: XCTestCase { } func testDictionaryAllNumber() { - var json:JSON = ["double":1.11111, "int":987654321] + var json: JSON = ["double": 1.11111, "int": 987654321] XCTAssertEqual(json.count, 2) var index = 0 - var dictionary = [String:NSNumber]() + var dictionary = [String: NSNumber]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.number! @@ -150,11 +150,11 @@ class SequenceTypeTests: XCTestCase { } func testDictionaryAllBool() { - var json:JSON = ["t":true, "f":false, "false":false, "tr":true, "true":true] + var json: JSON = ["t": true, "f": false, "false": false, "tr": true, "true": true] XCTAssertEqual(json.count, 5) var index = 0 - var dictionary = [String:Bool]() + var dictionary = [String: Bool]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.bool! @@ -167,11 +167,11 @@ class SequenceTypeTests: XCTestCase { } func testDictionaryAllString() { - var json:JSON = JSON(rawValue: ["a":"aoo","bb":"bpp","z":"zoo"] as NSDictionary)! + var json: JSON = JSON(rawValue: ["a": "aoo", "bb": "bpp", "z": "zoo"] as NSDictionary)! XCTAssertEqual(json.count, 3) var index = 0 - var dictionary = [String:String]() + var dictionary = [String: String]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.string! @@ -184,11 +184,11 @@ class SequenceTypeTests: XCTestCase { } func testDictionaryWithNull() { - var json:JSON = JSON(rawValue: ["a":"aoo","bb":"bpp","null":NSNull(), "z":"zoo"] as NSDictionary)! + var json: JSON = JSON(rawValue: ["a": "aoo", "bb": "bpp", "null": NSNull(), "z": "zoo"] as NSDictionary)! XCTAssertEqual(json.count, 4) var index = 0 - var dictionary = [String:AnyObject]() + var dictionary = [String: AnyObject]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.object as AnyObject? @@ -202,12 +202,12 @@ class SequenceTypeTests: XCTestCase { } func testDictionaryAllArray() { - var json:JSON = JSON (["Number":[NSNumber(value:1),NSNumber(value:2.123456),NSNumber(value:123456789)], "String":["aa","bbb","cccc"], "Mix":[true, "766", NSNull(), 655231.9823]]) + var json: JSON = JSON (["Number": [NSNumber(value:1), NSNumber(value:2.123456), NSNumber(value:123456789)], "String": ["aa", "bbb", "cccc"], "Mix": [true, "766", NSNull(), 655231.9823]]) XCTAssertEqual(json.count, 3) var index = 0 - var dictionary = [String:AnyObject]() + var dictionary = [String: AnyObject]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.object as AnyObject? diff --git a/Tests/SwiftyJSONTests/StringTests.swift b/Tests/SwiftyJSONTests/StringTests.swift index 8d8e6ebc..fb226fc5 100644 --- a/Tests/SwiftyJSONTests/StringTests.swift +++ b/Tests/SwiftyJSONTests/StringTests.swift @@ -35,7 +35,7 @@ class StringTests: XCTestCase { XCTAssertEqual(json.string!, "12345?67890.@#") XCTAssertEqual(json.stringValue, "12345?67890.@#") } - + func testUrl() { let json = JSON("http://github.com") XCTAssertEqual(json.url!, URL(string:"http://github.com")!) diff --git a/Tests/SwiftyJSONTests/SubscriptTests.swift b/Tests/SwiftyJSONTests/SubscriptTests.swift index 2a5cd97e..7c71a941 100644 --- a/Tests/SwiftyJSONTests/SubscriptTests.swift +++ b/Tests/SwiftyJSONTests/SubscriptTests.swift @@ -26,63 +26,63 @@ import SwiftyJSON class SubscriptTests: XCTestCase { func testArrayAllNumber() { - var json:JSON = [1,2.0,3.3,123456789,987654321.123456789] - XCTAssertTrue(json == [1,2.0,3.3,123456789,987654321.123456789]) + var json: JSON = [1, 2.0, 3.3, 123456789, 987654321.123456789] + XCTAssertTrue(json == [1, 2.0, 3.3, 123456789, 987654321.123456789]) XCTAssertTrue(json[0] == 1) XCTAssertEqual(json[1].double!, 2.0) XCTAssertTrue(json[2].floatValue == 3.3) XCTAssertEqual(json[3].int!, 123456789) XCTAssertEqual(json[4].doubleValue, 987654321.123456789) - + json[0] = 1.9 json[1] = 2.899 json[2] = 3.567 json[3] = 0.999 json[4] = 98732 - + XCTAssertTrue(json[0] == 1.9) XCTAssertEqual(json[1].doubleValue, 2.899) XCTAssertTrue(json[2] == 3.567) XCTAssertTrue(json[3].float! == 0.999) XCTAssertTrue(json[4].intValue == 98732) } - + func testArrayAllBool() { - var json:JSON = [true, false, false, true, true] + var json: JSON = [true, false, false, true, true] XCTAssertTrue(json == [true, false, false, true, true]) XCTAssertTrue(json[0] == true) XCTAssertTrue(json[1] == false) XCTAssertTrue(json[2] == false) XCTAssertTrue(json[3] == true) XCTAssertTrue(json[4] == true) - + json[0] = false json[4] = true XCTAssertTrue(json[0] == false) XCTAssertTrue(json[4] == true) } - + func testArrayAllString() { - var json:JSON = JSON(rawValue: ["aoo","bpp","zoo"] as NSArray)! - XCTAssertTrue(json == ["aoo","bpp","zoo"]) + var json: JSON = JSON(rawValue: ["aoo", "bpp", "zoo"] as NSArray)! + XCTAssertTrue(json == ["aoo", "bpp", "zoo"]) XCTAssertTrue(json[0] == "aoo") XCTAssertTrue(json[1] == "bpp") XCTAssertTrue(json[2] == "zoo") - + json[1] = "update" XCTAssertTrue(json[0] == "aoo") XCTAssertTrue(json[1] == "update") XCTAssertTrue(json[2] == "zoo") } - + func testArrayWithNull() { - var json:JSON = JSON(rawValue: ["aoo","bpp", NSNull() ,"zoo"] as NSArray)! + var json: JSON = JSON(rawValue: ["aoo", "bpp", NSNull(), "zoo"] as NSArray)! XCTAssertTrue(json[0] == "aoo") XCTAssertTrue(json[1] == "bpp") XCTAssertNil(json[2].string) XCTAssertNotNil(json[2].null) XCTAssertTrue(json[3] == "zoo") - + json[2] = "update" json[3] = JSON(NSNull()) XCTAssertTrue(json[0] == "aoo") @@ -91,27 +91,27 @@ class SubscriptTests: XCTestCase { XCTAssertNil(json[3].string) XCTAssertNotNil(json[3].null) } - + func testArrayAllDictionary() { - var json:JSON = [["1":1, "2":2], ["a":"A", "b":"B"], ["null":NSNull()]] - XCTAssertTrue(json[0] == ["1":1, "2":2]) - XCTAssertEqual(json[1].dictionary!, ["a":"A", "b":"B"]) - XCTAssertEqual(json[2], JSON(["null":NSNull()])) + var json: JSON = [["1": 1, "2": 2], ["a": "A", "b": "B"], ["null": NSNull()]] + XCTAssertTrue(json[0] == ["1": 1, "2": 2]) + XCTAssertEqual(json[1].dictionary!, ["a": "A", "b": "B"]) + XCTAssertEqual(json[2], JSON(["null": NSNull()])) XCTAssertTrue(json[0]["1"] == 1) XCTAssertTrue(json[0]["2"] == 2) XCTAssertEqual(json[1]["a"], JSON(rawValue: "A")!) XCTAssertEqual(json[1]["b"], JSON("B")) XCTAssertNotNil(json[2]["null"].null) - XCTAssertNotNil(json[2,"null"].null) - let keys:[JSONSubscriptType] = [1, "a"] + XCTAssertNotNil(json[2, "null"].null) + let keys: [JSONSubscriptType] = [1, "a"] XCTAssertEqual(json[keys], JSON(rawValue: "A")!) } - + func testDictionaryAllNumber() { - var json:JSON = ["double":1.11111, "int":987654321] + var json: JSON = ["double": 1.11111, "int": 987654321] XCTAssertEqual(json["double"].double!, 1.11111) XCTAssertTrue(json["int"] == 987654321) - + json["double"] = 2.2222 json["int"] = 123456789 json["add"] = 7890 @@ -119,9 +119,9 @@ class SubscriptTests: XCTestCase { XCTAssertEqual(json["int"].doubleValue, 123456789.0) XCTAssertEqual(json["add"].intValue, 7890) } - + func testDictionaryAllBool() { - var json:JSON = ["t":true, "f":false, "false":false, "tr":true, "true":true] + var json: JSON = ["t": true, "f": false, "false": false, "tr": true, "true": true] XCTAssertTrue(json["t"] == true) XCTAssertTrue(json["f"] == false) XCTAssertTrue(json["false"] == false) @@ -133,61 +133,61 @@ class SubscriptTests: XCTestCase { XCTAssertTrue(json["f"] == true) XCTAssertTrue(json["tr"] == JSON(false)) } - + func testDictionaryAllString() { - var json:JSON = JSON(rawValue: ["a":"aoo","bb":"bpp","z":"zoo"] as NSDictionary)! + var json: JSON = JSON(rawValue: ["a": "aoo", "bb": "bpp", "z": "zoo"] as NSDictionary)! XCTAssertTrue(json["a"] == "aoo") XCTAssertEqual(json["bb"], JSON("bpp")) XCTAssertTrue(json["z"] == "zoo") - + json["bb"] = "update" XCTAssertTrue(json["a"] == "aoo") XCTAssertTrue(json["bb"] == "update") XCTAssertTrue(json["z"] == "zoo") } - + func testDictionaryWithNull() { - var json:JSON = JSON(rawValue: ["a":"aoo","bb":"bpp","null":NSNull(), "z":"zoo"] as NSDictionary)! + var json: JSON = JSON(rawValue: ["a": "aoo", "bb": "bpp", "null": NSNull(), "z": "zoo"] as NSDictionary)! XCTAssertTrue(json["a"] == "aoo") XCTAssertEqual(json["bb"], JSON("bpp")) XCTAssertEqual(json["null"], JSON(NSNull())) XCTAssertTrue(json["z"] == "zoo") - + json["null"] = "update" XCTAssertTrue(json["a"] == "aoo") XCTAssertTrue(json["null"] == "update") XCTAssertTrue(json["z"] == "zoo") } - + func testDictionaryAllArray() { //Swift bug: [1, 2.01,3.09] is convert to [1, 2, 3] (Array) - let json:JSON = JSON ([[NSNumber(value:1),NSNumber(value:2.123456),NSNumber(value:123456789)], ["aa","bbb","cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) - XCTAssertTrue(json[0] == [1,2.123456,123456789]) + let json: JSON = JSON ([[NSNumber(value:1), NSNumber(value:2.123456), NSNumber(value:123456789)], ["aa", "bbb", "cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) + XCTAssertTrue(json[0] == [1, 2.123456, 123456789]) XCTAssertEqual(json[0][1].double!, 2.123456) XCTAssertTrue(json[0][2] == 123456789) XCTAssertTrue(json[1][0] == "aa") - XCTAssertTrue(json[1] == ["aa","bbb","cccc"]) + XCTAssertTrue(json[1] == ["aa", "bbb", "cccc"]) XCTAssertTrue(json[2][0] == true) XCTAssertTrue(json[2][1] == "766") - XCTAssertTrue(json[[2,1]] == "766") + XCTAssertTrue(json[[2, 1]] == "766") XCTAssertEqual(json[2][2], JSON(NSNull())) - XCTAssertEqual(json[2,2], JSON(NSNull())) + XCTAssertEqual(json[2, 2], JSON(NSNull())) XCTAssertEqual(json[2][3], JSON(655231.9823)) - XCTAssertEqual(json[2,3], JSON(655231.9823)) - XCTAssertEqual(json[[2,3]], JSON(655231.9823)) + XCTAssertEqual(json[2, 3], JSON(655231.9823)) + XCTAssertEqual(json[[2, 3]], JSON(655231.9823)) } - + func testOutOfBounds() { - let json:JSON = JSON ([[NSNumber(value:1),NSNumber(value:2.123456),NSNumber(value:123456789)], ["aa","bbb","cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) + let json: JSON = JSON ([[NSNumber(value:1), NSNumber(value:2.123456), NSNumber(value:123456789)], ["aa", "bbb", "cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) XCTAssertEqual(json[9], JSON.null) XCTAssertEqual(json[-2].error!.code, ErrorIndexOutOfBounds) XCTAssertEqual(json[6].error!.code, ErrorIndexOutOfBounds) XCTAssertEqual(json[9][8], JSON.null) XCTAssertEqual(json[8][7].error!.code, ErrorIndexOutOfBounds) - XCTAssertEqual(json[8,7].error!.code, ErrorIndexOutOfBounds) + XCTAssertEqual(json[8, 7].error!.code, ErrorIndexOutOfBounds) XCTAssertEqual(json[999].error!.code, ErrorIndexOutOfBounds) } - + func testErrorWrongType() { let json = JSON(12345) XCTAssertEqual(json[9], JSON.null) @@ -198,68 +198,68 @@ class SubscriptTests: XCTestCase { XCTAssertEqual(json[0]["name"].error!.code, ErrorWrongType) XCTAssertEqual(json["type"]["name"].error!.code, ErrorWrongType) XCTAssertEqual(json["name"][99].error!.code, ErrorWrongType) - XCTAssertEqual(json[1,"Value"].error!.code, ErrorWrongType) - XCTAssertEqual(json[1, 2,"Value"].error!.code, ErrorWrongType) - XCTAssertEqual(json[[1, 2,"Value"]].error!.code, ErrorWrongType) + XCTAssertEqual(json[1, "Value"].error!.code, ErrorWrongType) + XCTAssertEqual(json[1, 2, "Value"].error!.code, ErrorWrongType) + XCTAssertEqual(json[[1, 2, "Value"]].error!.code, ErrorWrongType) } - + func testErrorNotExist() { - let json:JSON = ["name":"NAME", "age":15] + let json: JSON = ["name": "NAME", "age": 15] XCTAssertEqual(json["Type"], JSON.null) XCTAssertEqual(json["Type"].error!.code, ErrorNotExist) XCTAssertEqual(json["Type"][1].error!.code, ErrorNotExist) XCTAssertEqual(json["Type", 1].error!.code, ErrorNotExist) XCTAssertEqual(json["Type"]["Value"].error!.code, ErrorNotExist) - XCTAssertEqual(json["Type","Value"].error!.code, ErrorNotExist) + XCTAssertEqual(json["Type", "Value"].error!.code, ErrorNotExist) } - + func testMultilevelGetter() { - let json:JSON = [[[[["one":1]]]]] + let json: JSON = [[[[["one": 1]]]]] XCTAssertEqual(json[[0, 0, 0, 0, "one"]].int!, 1) XCTAssertEqual(json[0, 0, 0, 0, "one"].int!, 1) XCTAssertEqual(json[0][0][0][0]["one"].int!, 1) } - + func testMultilevelSetter1() { - var json:JSON = [[[[["num":1]]]]] + var json: JSON = [[[[["num": 1]]]]] json[0, 0, 0, 0, "num"] = 2 XCTAssertEqual(json[[0, 0, 0, 0, "num"]].intValue, 2) json[0, 0, 0, 0, "num"] = JSON.null XCTAssertEqual(json[0, 0, 0, 0, "num"].null!, NSNull()) json[0, 0, 0, 0, "num"] = 100.009 XCTAssertEqual(json[0][0][0][0]["num"].doubleValue, 100.009) - json[[0, 0, 0, 0]] = ["name":"Jack"] - XCTAssertEqual(json[0,0,0,0,"name"].stringValue, "Jack") + json[[0, 0, 0, 0]] = ["name": "Jack"] + XCTAssertEqual(json[0, 0, 0, 0, "name"].stringValue, "Jack") XCTAssertEqual(json[0][0][0][0]["name"].stringValue, "Jack") - XCTAssertEqual(json[[0,0,0,0,"name"]].stringValue, "Jack") - json[[0,0,0,0,"name"]].string = "Mike" - XCTAssertEqual(json[0,0,0,0,"name"].stringValue, "Mike") - let path:[JSONSubscriptType] = [0,0,0,0,"name"] + XCTAssertEqual(json[[0, 0, 0, 0, "name"]].stringValue, "Jack") + json[[0, 0, 0, 0, "name"]].string = "Mike" + XCTAssertEqual(json[0, 0, 0, 0, "name"].stringValue, "Mike") + let path: [JSONSubscriptType] = [0, 0, 0, 0, "name"] json[path].string = "Jim" XCTAssertEqual(json[path].stringValue, "Jim") } - + func testMultilevelSetter2() { - var json:JSON = ["user":["id":987654, "info":["name":"jack","email":"jack@gmail.com"], "feeds":[98833,23443,213239,23232]]] - json["user","info","name"] = "jim" - XCTAssertEqual(json["user","id"], 987654) - XCTAssertEqual(json["user","info","name"], "jim") - XCTAssertEqual(json["user","info","email"], "jack@gmail.com") - XCTAssertEqual(json["user","feeds"], [98833,23443,213239,23232]) - json["user","info","email"] = "jim@hotmail.com" - XCTAssertEqual(json["user","id"], 987654) - XCTAssertEqual(json["user","info","name"], "jim") - XCTAssertEqual(json["user","info","email"], "jim@hotmail.com") - XCTAssertEqual(json["user","feeds"], [98833,23443,213239,23232]) - json["user","info"] = ["name":"tom","email":"tom@qq.com"] - XCTAssertEqual(json["user","id"], 987654) - XCTAssertEqual(json["user","info","name"], "tom") - XCTAssertEqual(json["user","info","email"], "tom@qq.com") - XCTAssertEqual(json["user","feeds"], [98833,23443,213239,23232]) - json["user","feeds"] = [77323,2313,4545,323] - XCTAssertEqual(json["user","id"], 987654) - XCTAssertEqual(json["user","info","name"], "tom") - XCTAssertEqual(json["user","info","email"], "tom@qq.com") - XCTAssertEqual(json["user","feeds"], [77323,2313,4545,323]) + var json: JSON = ["user": ["id": 987654, "info": ["name": "jack", "email": "jack@gmail.com"], "feeds": [98833, 23443, 213239, 23232]]] + json["user", "info", "name"] = "jim" + XCTAssertEqual(json["user", "id"], 987654) + XCTAssertEqual(json["user", "info", "name"], "jim") + XCTAssertEqual(json["user", "info", "email"], "jack@gmail.com") + XCTAssertEqual(json["user", "feeds"], [98833, 23443, 213239, 23232]) + json["user", "info", "email"] = "jim@hotmail.com" + XCTAssertEqual(json["user", "id"], 987654) + XCTAssertEqual(json["user", "info", "name"], "jim") + XCTAssertEqual(json["user", "info", "email"], "jim@hotmail.com") + XCTAssertEqual(json["user", "feeds"], [98833, 23443, 213239, 23232]) + json["user", "info"] = ["name": "tom", "email": "tom@qq.com"] + XCTAssertEqual(json["user", "id"], 987654) + XCTAssertEqual(json["user", "info", "name"], "tom") + XCTAssertEqual(json["user", "info", "email"], "tom@qq.com") + XCTAssertEqual(json["user", "feeds"], [98833, 23443, 213239, 23232]) + json["user", "feeds"] = [77323, 2313, 4545, 323] + XCTAssertEqual(json["user", "id"], 987654) + XCTAssertEqual(json["user", "info", "name"], "tom") + XCTAssertEqual(json["user", "info", "email"], "tom@qq.com") + XCTAssertEqual(json["user", "feeds"], [77323, 2313, 4545, 323]) } } From d02ca810a338240bc10a67b8e471f0373d2be868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=81=E5=B8=85?= Date: Mon, 20 Feb 2017 09:30:47 +0800 Subject: [PATCH 139/260] Fix a spelling mistake and simplify initialize methods invoking --- Tests/SwiftyJSONTests/NestedJSONTests.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/SwiftyJSONTests/NestedJSONTests.swift b/Tests/SwiftyJSONTests/NestedJSONTests.swift index 17305384..1e00903a 100644 --- a/Tests/SwiftyJSONTests/NestedJSONTests.swift +++ b/Tests/SwiftyJSONTests/NestedJSONTests.swift @@ -54,18 +54,18 @@ class NestedJSONTests: XCTestCase { XCTAssertEqual(json["c"]["aa"].string, "11") } - func testNextedJSON() { - let inner = JSON.init([ + func testNestedJSON() { + let inner = JSON([ "some_field": "1" + "2", ]) - let json = JSON.init([ + let json = JSON([ "outer_field": "1" + "2", "inner_json": inner ]) XCTAssertEqual(json["inner_json"], ["some_field": "12"]) let foo = "foo" - let json2 = JSON.init([ + let json2 = JSON([ "outer_field": foo, "inner_json": inner ]) From 3c1ab40abec704c1caf2484a4b288476c3add40a Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Mon, 20 Feb 2017 22:35:51 +0800 Subject: [PATCH 140/260] [Tests] Improve SwiftyJSON Mutability test cases --- SwiftyJSON.xcodeproj/project.pbxproj | 8 ++ Tests/SwiftyJSONTests/MutabilityTests.swift | 106 ++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 Tests/SwiftyJSONTests/MutabilityTests.swift diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 183662cd..0ca5df39 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -39,6 +39,9 @@ A819C49F19E2EE5B00ADCC3D /* SubscriptTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */; }; A819C4A119E37FC600ADCC3D /* PrintableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A819C4A019E37FC600ADCC3D /* PrintableTests.swift */; }; A81CBA0B1BCF6B0200A649A2 /* Tests.json in Resources */ = {isa = PBXBuildFile; fileRef = A885D1DA19CFCFF0002FD4C3 /* Tests.json */; }; + A830A6951E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */; }; + A830A6961E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */; }; + A830A6971E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */; }; A8491E1E19CD6DAE00CCFAE6 /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8491E1D19CD6DAE00CCFAE6 /* SwiftyJSON.swift */; }; A8580F791BCF5C5B00DA927B /* SwiftyJSON.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7236B4F61BAC14150020529B /* SwiftyJSON.framework */; }; A8580F801BCF69A000DA927B /* PerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A86BAA0D19EBC32B009EAAEB /* PerformanceTests.swift */; }; @@ -110,6 +113,7 @@ A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SubscriptTests.swift; sourceTree = ""; }; A819C4A019E37FC600ADCC3D /* PrintableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrintableTests.swift; sourceTree = ""; }; A82A1C0D19D922DC009A653D /* Info-iOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; + A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutabilityTests.swift; sourceTree = ""; }; A8491E1D19CD6DAE00CCFAE6 /* SwiftyJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftyJSON.swift; sourceTree = ""; }; A8580F741BCF5C5B00DA927B /* SwiftyJSON tvOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON tvOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; A8580F781BCF5C5B00DA927B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-tvOS.plist"; sourceTree = ""; }; @@ -245,6 +249,7 @@ A87080E719E439DA00CDE086 /* NumberTests.swift */, A863BE2719EED46F0092A41F /* RawTests.swift */, A8B66C8B19E51D6500540692 /* DictionaryTests.swift */, + A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */, A8B66C8D19E52F4200540692 /* ArrayTests.swift */, 2E4FEFEB19575BE100351305 /* Supporting Files */, ); @@ -562,6 +567,7 @@ A86BAA0E19EBC32B009EAAEB /* PerformanceTests.swift in Sources */, A819C49919E1B10300ADCC3D /* RawRepresentableTests.swift in Sources */, A819C49F19E2EE5B00ADCC3D /* SubscriptTests.swift in Sources */, + A830A6951E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */, A863BE2819EED46F0092A41F /* RawTests.swift in Sources */, A885D1D219CF1EE6002FD4C3 /* BaseTests.swift in Sources */, A8B66C8E19E52F4200540692 /* ArrayTests.swift in Sources */, @@ -600,6 +606,7 @@ 9C459F021A9103C1008C9A41 /* NumberTests.swift in Sources */, 9C459EFF1A9103C1008C9A41 /* RawRepresentableTests.swift in Sources */, 9C459EFA1A9103C1008C9A41 /* BaseTests.swift in Sources */, + A830A6961E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */, 9C459F041A9103C1008C9A41 /* DictionaryTests.swift in Sources */, 9C459EF91A9103C1008C9A41 /* PerformanceTests.swift in Sources */, 9C459EFE1A9103C1008C9A41 /* LiteralConvertibleTests.swift in Sources */, @@ -622,6 +629,7 @@ A8580F821BCF69A000DA927B /* SequenceTypeTests.swift in Sources */, A8580F831BCF69A000DA927B /* PrintableTests.swift in Sources */, A8580F841BCF69A000DA927B /* SubscriptTests.swift in Sources */, + A830A6971E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */, A8580F851BCF69A000DA927B /* LiteralConvertibleTests.swift in Sources */, A8580F861BCF69A000DA927B /* RawRepresentableTests.swift in Sources */, A8580F871BCF69A000DA927B /* ComparableTests.swift in Sources */, diff --git a/Tests/SwiftyJSONTests/MutabilityTests.swift b/Tests/SwiftyJSONTests/MutabilityTests.swift new file mode 100644 index 00000000..a6a20310 --- /dev/null +++ b/Tests/SwiftyJSONTests/MutabilityTests.swift @@ -0,0 +1,106 @@ +// DictionaryTests.swift +// +// Copyright (c) 2014 - 2017 Zigii Wong +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import XCTest +import SwiftyJSON + +class MutabilityTest: XCTestCase { + + func testDictionaryJSONMutability() { + let dictionary: [String: Any] = [ + "string": "STRING", + "number": 9823.212, + "bool": true, + "empty": ["nothing"] + ] + + var json = JSON(dictionary) + XCTAssertEqual(json["string"], "STRING") + XCTAssertEqual(json["number"], 9823.212) + XCTAssertEqual(json["bool"], true) + XCTAssertEqual(json["empty"], ["nothing"]) + + json["string"] = "muted" + XCTAssertEqual(json["string"], "muted") + + json["number"] = 9999.0 + XCTAssertEqual(json["number"], 9999.0) + + json["bool"] = false + XCTAssertEqual(json["bool"], false) + + json["empty"] = [] + XCTAssertEqual(json["empty"], []) + + json["new"] = JSON(["foo": "bar"]) + XCTAssertEqual(json["new"], ["foo": "bar"]) + } + + func testArrayJSONMutability() { + let array: [Any] = ["1", "2", 3, true, []] + + var json = JSON(array) + XCTAssertEqual(json[0], "1") + XCTAssertEqual(json[1], "2") + XCTAssertEqual(json[2], 3) + XCTAssertEqual(json[3], true) + XCTAssertEqual(json[4], []) + + json[0] = false + XCTAssertEqual(json[0], false) + + json[1] = 2 + XCTAssertEqual(json[1], 2) + + json[2] = "3" + XCTAssertEqual(json[2], "3") + + json[3] = [:] + XCTAssertEqual(json[3], [:]) + + json[4] = [1, 2] + XCTAssertEqual(json[4], [1, 2]) + } + + func testValueMutability() { + var intArray = JSON([0, 1, 2]) + intArray[0] = JSON(55) + XCTAssertEqual(intArray[0], 55) + XCTAssertEqual(intArray[0].intValue, 55) + + var dictionary = JSON(["foo": "bar"]) + dictionary["foo"] = JSON("foo") + XCTAssertEqual(dictionary["foo"], "foo") + XCTAssertEqual(dictionary["foo"].stringValue, "foo") + + var number = JSON(1) + number = JSON("111") + XCTAssertEqual(number, "111") + XCTAssertEqual(number.intValue, 111) + XCTAssertEqual(number.stringValue, "111") + + var boolean = JSON(true) + boolean = JSON(false) + XCTAssertEqual(boolean, false) + XCTAssertEqual(boolean.boolValue, false) + } +} From ddd18f423193aede05f0f2873b945695086d4d8e Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 21 Feb 2017 00:53:31 +0800 Subject: [PATCH 141/260] [SwiftLint] Satisfy operator_whitespace rule --- .swiftlint.yml | 1 - Source/SwiftyJSON.swift | 26 +++++++++++++------------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index 1a5ad564..689e2e3d 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -7,7 +7,6 @@ disabled_rules: - line_length - type_body_length - implicit_getter - - operator_whitespace - cyclomatic_complexity - function_body_length - control_statement diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 8cd2d86e..afecb213 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -286,7 +286,7 @@ public enum Index: Comparable { case dictionary(DictionaryIndex) case null - static public func ==(lhs: Index, rhs: Index) -> Bool { + static public func == (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right @@ -298,7 +298,7 @@ public enum Index: Comparable { } } - static public func <(lhs: Index, rhs: Index) -> Bool { + static public func < (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right @@ -1292,7 +1292,7 @@ extension JSON { // MARK: - Comparable extension JSON : Swift.Comparable {} -public func ==(lhs: JSON, rhs: JSON) -> Bool { +public func == (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): @@ -1312,7 +1312,7 @@ public func ==(lhs: JSON, rhs: JSON) -> Bool { } } -public func <=(lhs: JSON, rhs: JSON) -> Bool { +public func <= (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): @@ -1332,7 +1332,7 @@ public func <=(lhs: JSON, rhs: JSON) -> Bool { } } -public func >=(lhs: JSON, rhs: JSON) -> Bool { +public func >= (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): @@ -1352,7 +1352,7 @@ public func >=(lhs: JSON, rhs: JSON) -> Bool { } } -public func >(lhs: JSON, rhs: JSON) -> Bool { +public func > (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): @@ -1364,7 +1364,7 @@ public func >(lhs: JSON, rhs: JSON) -> Bool { } } -public func <(lhs: JSON, rhs: JSON) -> Bool { +public func < (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): @@ -1396,7 +1396,7 @@ extension NSNumber { } } -func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { +func == (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false @@ -1407,11 +1407,11 @@ func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { } } -func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { +func != (lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } -func <(lhs: NSNumber, rhs: NSNumber) -> Bool { +func < (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): @@ -1423,7 +1423,7 @@ func <(lhs: NSNumber, rhs: NSNumber) -> Bool { } } -func >(lhs: NSNumber, rhs: NSNumber) -> Bool { +func > (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): @@ -1435,7 +1435,7 @@ func >(lhs: NSNumber, rhs: NSNumber) -> Bool { } } -func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { +func <= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): @@ -1447,7 +1447,7 @@ func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { } } -func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { +func >= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): From 831b47e0d50d7143a3db1e452be1572b4055b7b0 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 21 Feb 2017 01:01:13 +0800 Subject: [PATCH 142/260] [SwiftLint] Satisfy implicit_getter rule --- .swiftlint.yml | 1 - Source/SwiftyJSON.swift | 34 ++++++++++++++-------------------- 2 files changed, 14 insertions(+), 21 deletions(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index 689e2e3d..cfa450e5 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -6,7 +6,6 @@ disabled_rules: - file_length - line_length - type_body_length - - implicit_getter - cyclomatic_complexity - function_body_length - control_statement diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index afecb213..3155cc9a 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -270,15 +270,15 @@ public struct JSON { } /// JSON type - public var type: Type { get { return _type } } + public var type: Type { return _type } /// Error in JSON - public var error: NSError? { get { return self._error } } + public var error: NSError? { return self._error } /// The static null JSON @available(*, unavailable, renamed:"null") - public static var nullJSON: JSON { get { return null } } - public static var null: JSON { get { return JSON(NSNull()) } } + public static var nullJSON: JSON { return null } + public static var null: JSON { return JSON(NSNull()) } } public enum Index: Comparable { @@ -756,20 +756,16 @@ extension JSON { //Optional [JSON] public var array: [JSON]? { - get { - if self.type == .array { - return self.rawArray.map { JSON($0) } - } else { - return nil - } + if self.type == .array { + return self.rawArray.map { JSON($0) } + } else { + return nil } } //Non-optional [JSON] public var arrayValue: [JSON] { - get { - return self.array ?? [] - } + return self.array ?? [] } //Optional [Any] @@ -1385,13 +1381,11 @@ private let falseObjCType = String(cString: falseNumber.objCType) extension NSNumber { var isBool: Bool { - get { - let objCType = String(cString: self.objCType) - if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { - return true - } else { - return false - } + let objCType = String(cString: self.objCType) + if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { + return true + } else { + return false } } } From 024efa4e123d80d09e927c44eb51f8c34c5ef5b6 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 21 Feb 2017 01:03:34 +0800 Subject: [PATCH 143/260] [SwiftLint] Remove parentheses of conditional --- .swiftlint.yml | 1 - Source/SwiftyJSON.swift | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index cfa450e5..03003d1d 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -8,4 +8,3 @@ disabled_rules: - type_body_length - cyclomatic_complexity - function_body_length - - control_statement diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 3155cc9a..b975501f 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -650,7 +650,7 @@ extension JSON: Swift.RawRepresentable { options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10 ) throws -> String? { - if (maxObjectDepth < 0) { + if maxObjectDepth < 0 { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop"]) } switch self.type { From 8936353a9c17b64e37ee72ac088dc8139ab33a3d Mon Sep 17 00:00:00 2001 From: Jobins John Date: Wed, 22 Feb 2017 09:32:49 +0400 Subject: [PATCH 144/260] Updated Year in License File --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 916a0acd..68e3fd74 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016 Ruoyu Fu +Copyright (c) 2017 Ruoyu Fu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 0e986772b1888181e54f60dae44090bb7947a0eb Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 22 Feb 2017 23:51:03 +0800 Subject: [PATCH 145/260] Add github ISSUE and PULL_REQUEST TEMPLATE --- ISSUE_TEMPLATE | 33 +++++++++++++++++++++++++++++++++ PULL_REQUEST_TEMPLATE | 13 +++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 ISSUE_TEMPLATE create mode 100644 PULL_REQUEST_TEMPLATE diff --git a/ISSUE_TEMPLATE b/ISSUE_TEMPLATE new file mode 100644 index 00000000..eb2ba192 --- /dev/null +++ b/ISSUE_TEMPLATE @@ -0,0 +1,33 @@ +### What did you do? + +Please replace this with what you did. + +### What did you expect to happen? + +Please replace this with what you expected to happen. + +### What actually happened instead? + +Please replace this with what happened instead. + +### Environment + +List the software versions you're using: + + - SwiftyJSON: *?.?.?* + - Xcode Version: *?.? (????)* (Open Xcode; In menubar: Xcode > About Xcode) + - Swift Version: *?.?* (Open Xcode Preferences; Components > Toolchains. If none, use `Xcode Default`.) + +Please also mention which package manager you used and its version. Delete the +other package managers in this list: + + - Cocoapods: *?.?.?* (Use `pod --version` in Terminal) + - Carthage: *?.?* (Use `carthage version` in Terminal) + - Swift Package Manager *?.?.? (swiftpm-???)* (Use `swift build --version` in Terminal) + +### Project that demonstrates the issue + +Please link to a project we can download that reproduces the issue. Feel free +to delete this section if it's not relevant to the issue (eg - feature request). + +The project should be [short, self-contained, and correct example](http://sscce.org/). \ No newline at end of file diff --git a/PULL_REQUEST_TEMPLATE b/PULL_REQUEST_TEMPLATE new file mode 100644 index 00000000..5efff141 --- /dev/null +++ b/PULL_REQUEST_TEMPLATE @@ -0,0 +1,13 @@ +The PR should summarize what was changed and why. Here are some questions to +help you if you're not sure: + + - What behavior was changed? + - What code was refactored / updated to support this change? + - What issues are related to this PR? Or why was this change introduced? + +Checklist - While not every PR needs it, new features should consider this list: + + - [ ] Does this have tests? + - [ ] Does this have documentation? + - [ ] Does this break the public API (Requires major version bump)? + - [ ] Is this a new feature (Requires minor version bump)? \ No newline at end of file From cc071b333729c06687277d51a469824c2ca785d9 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Thu, 23 Feb 2017 21:54:34 +0800 Subject: [PATCH 146/260] Move files into .github directory --- ISSUE_TEMPLATE => .github/ISSUE_TEMPLATE | 0 PULL_REQUEST_TEMPLATE => .github/PULL_REQUEST_TEMPLATE | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename ISSUE_TEMPLATE => .github/ISSUE_TEMPLATE (100%) rename PULL_REQUEST_TEMPLATE => .github/PULL_REQUEST_TEMPLATE (100%) diff --git a/ISSUE_TEMPLATE b/.github/ISSUE_TEMPLATE similarity index 100% rename from ISSUE_TEMPLATE rename to .github/ISSUE_TEMPLATE diff --git a/PULL_REQUEST_TEMPLATE b/.github/PULL_REQUEST_TEMPLATE similarity index 100% rename from PULL_REQUEST_TEMPLATE rename to .github/PULL_REQUEST_TEMPLATE From 0417977cead785f51054da08dfca970a303623da Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Sat, 25 Feb 2017 02:01:57 +0800 Subject: [PATCH 147/260] [SwiftLint] Corrected Trailing Whitespace --- Example/Example/ViewController.swift | 2 +- Source/SwiftyJSON.swift | 2 +- Tests/SwiftyJSONTests/MutabilityTests.swift | 36 ++++++++++----------- Tests/SwiftyJSONTests/NestedJSONTests.swift | 12 +++---- 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index ecca7acb..12a05290 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -32,7 +32,7 @@ class ViewController: UITableViewController { override func viewDidLoad() { self.title = "SwiftyJSON(\(json.type))" } - + override func numberOfSections(in tableView: UITableView) -> Int { return 1 } diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index a17db1e3..f5e16e47 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -531,7 +531,7 @@ extension JSON: Swift.ExpressibleByFloatLiteral { extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { - var dictionary = [String : Any](minimumCapacity: elements.count) + var dictionary = [String: Any](minimumCapacity: elements.count) for (k, v) in elements { dictionary[k] = v } diff --git a/Tests/SwiftyJSONTests/MutabilityTests.swift b/Tests/SwiftyJSONTests/MutabilityTests.swift index a6a20310..6a48cf79 100644 --- a/Tests/SwiftyJSONTests/MutabilityTests.swift +++ b/Tests/SwiftyJSONTests/MutabilityTests.swift @@ -24,7 +24,7 @@ import XCTest import SwiftyJSON class MutabilityTest: XCTestCase { - + func testDictionaryJSONMutability() { let dictionary: [String: Any] = [ "string": "STRING", @@ -32,72 +32,72 @@ class MutabilityTest: XCTestCase { "bool": true, "empty": ["nothing"] ] - + var json = JSON(dictionary) XCTAssertEqual(json["string"], "STRING") XCTAssertEqual(json["number"], 9823.212) XCTAssertEqual(json["bool"], true) XCTAssertEqual(json["empty"], ["nothing"]) - + json["string"] = "muted" XCTAssertEqual(json["string"], "muted") - + json["number"] = 9999.0 XCTAssertEqual(json["number"], 9999.0) - + json["bool"] = false XCTAssertEqual(json["bool"], false) - + json["empty"] = [] XCTAssertEqual(json["empty"], []) - + json["new"] = JSON(["foo": "bar"]) XCTAssertEqual(json["new"], ["foo": "bar"]) } - + func testArrayJSONMutability() { let array: [Any] = ["1", "2", 3, true, []] - + var json = JSON(array) XCTAssertEqual(json[0], "1") XCTAssertEqual(json[1], "2") XCTAssertEqual(json[2], 3) XCTAssertEqual(json[3], true) XCTAssertEqual(json[4], []) - + json[0] = false XCTAssertEqual(json[0], false) - + json[1] = 2 XCTAssertEqual(json[1], 2) - + json[2] = "3" XCTAssertEqual(json[2], "3") - + json[3] = [:] XCTAssertEqual(json[3], [:]) - + json[4] = [1, 2] XCTAssertEqual(json[4], [1, 2]) } - + func testValueMutability() { var intArray = JSON([0, 1, 2]) intArray[0] = JSON(55) XCTAssertEqual(intArray[0], 55) XCTAssertEqual(intArray[0].intValue, 55) - + var dictionary = JSON(["foo": "bar"]) dictionary["foo"] = JSON("foo") XCTAssertEqual(dictionary["foo"], "foo") XCTAssertEqual(dictionary["foo"].stringValue, "foo") - + var number = JSON(1) number = JSON("111") XCTAssertEqual(number, "111") XCTAssertEqual(number.intValue, 111) XCTAssertEqual(number.stringValue, "111") - + var boolean = JSON(true) boolean = JSON(false) XCTAssertEqual(boolean, false) diff --git a/Tests/SwiftyJSONTests/NestedJSONTests.swift b/Tests/SwiftyJSONTests/NestedJSONTests.swift index b861c5a0..18bac5ef 100644 --- a/Tests/SwiftyJSONTests/NestedJSONTests.swift +++ b/Tests/SwiftyJSONTests/NestedJSONTests.swift @@ -39,31 +39,31 @@ class NestedJSONTests: XCTestCase { ] XCTAssertNotNil(try? nestedFamily.rawData()) } - + func testArrayJSON() { let arr: [JSON] = ["a", 1, ["b", 2]] let json = JSON(arr) XCTAssertEqual(json[0].string, "a") - XCTAssertEqual(json[2,1].int, 2) + XCTAssertEqual(json[2, 1].int, 2) } - + func testDictionaryJSON() { let json: JSON = ["a": JSON("1"), "b": JSON([1, 2, "3"]), "c": JSON(["aa": "11", "bb": 22])] XCTAssertEqual(json["a"].string, "1") XCTAssertEqual(json["b"].array!, [1, 2, "3"]) XCTAssertEqual(json["c"]["aa"].string, "11") } - + func testNestedJSON() { let inner = JSON([ - "some_field": "1" + "2", + "some_field": "1" + "2" ]) let json = JSON([ "outer_field": "1" + "2", "inner_json": inner ]) XCTAssertEqual(json["inner_json"], ["some_field": "12"]) - + let foo = "foo" let json2 = JSON([ "outer_field": foo, From 41f547272db2afef4def3d441d9670f49e23f637 Mon Sep 17 00:00:00 2001 From: Simon Strandgaard Date: Sun, 26 Feb 2017 13:26:33 +0000 Subject: [PATCH 148/260] RawTests.testNestedJSON() added --- Tests/SwiftyJSONTests/RawTests.swift | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Tests/SwiftyJSONTests/RawTests.swift b/Tests/SwiftyJSONTests/RawTests.swift index faa043a1..80068e38 100644 --- a/Tests/SwiftyJSONTests/RawTests.swift +++ b/Tests/SwiftyJSONTests/RawTests.swift @@ -92,4 +92,18 @@ class RawTests: XCTestCase { let json: JSON = JSON.null XCTAssertEqual(json.rawString(), "null") } + + func testNestedJSON() { + let inner: JSON = ["name": "john doe"] + let json: JSON = ["level": 1337, "user": inner] + let data: Data? + do { + data = try json.rawData() + } catch _ { + data = nil + } + let string = json.rawString() + XCTAssertNotNil(data) + XCTAssertNotNil(string) + } } From 71cae94f2ae3900369d0c760710bbc332614ac90 Mon Sep 17 00:00:00 2001 From: Simon Strandgaard Date: Sun, 26 Feb 2017 13:41:30 +0000 Subject: [PATCH 149/260] Converted tabs to spaces --- Tests/SwiftyJSONTests/RawTests.swift | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Tests/SwiftyJSONTests/RawTests.swift b/Tests/SwiftyJSONTests/RawTests.swift index 80068e38..e30de39d 100644 --- a/Tests/SwiftyJSONTests/RawTests.swift +++ b/Tests/SwiftyJSONTests/RawTests.swift @@ -92,18 +92,18 @@ class RawTests: XCTestCase { let json: JSON = JSON.null XCTAssertEqual(json.rawString(), "null") } - - func testNestedJSON() { - let inner: JSON = ["name": "john doe"] - let json: JSON = ["level": 1337, "user": inner] - let data: Data? - do { - data = try json.rawData() - } catch _ { - data = nil - } - let string = json.rawString() - XCTAssertNotNil(data) - XCTAssertNotNil(string) - } + + func testNestedJSON() { + let inner: JSON = ["name": "john doe"] + let json: JSON = ["level": 1337, "user": inner] + let data: Data? + do { + data = try json.rawData() + } catch _ { + data = nil + } + let string = json.rawString() + XCTAssertNotNil(data) + XCTAssertNotNil(string) + } } From de70760ff5c065a4397e5429e162398a1ab2db66 Mon Sep 17 00:00:00 2001 From: Michel Tabari Date: Tue, 4 Apr 2017 15:45:53 +0200 Subject: [PATCH 150/260] Fix spelling mistake --- Source/SwiftyJSON.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index f5e16e47..fc6f6afd 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -184,7 +184,7 @@ public struct JSON { fileprivate var rawBool: Bool = false /// Private type fileprivate var _type: Type = .null - /// prviate error + /// Private error fileprivate var _error: NSError? /// Object in JSON From d106438eb21345a526c840340ec62594f64484e0 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Sun, 16 Apr 2017 17:06:31 +0800 Subject: [PATCH 151/260] [SwiftLint] Prefer `!= nil` over `let _` --- Source/SwiftyJSON.swift | 2 +- Tests/SwiftyJSONTests/BaseTests.swift | 4 ++-- Tests/SwiftyJSONTests/RawRepresentableTests.swift | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index fc6f6afd..1cf847c5 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -951,7 +951,7 @@ extension JSON { switch self.type { case .string: // Check for existing percent escapes first to prevent double-escaping of % character - if let _ = self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) { + if self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { return Foundation.URL(string: self.rawString) } else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift index 80bb9893..81e05697 100644 --- a/Tests/SwiftyJSONTests/BaseTests.swift +++ b/Tests/SwiftyJSONTests/BaseTests.swift @@ -226,13 +226,13 @@ class BaseTests: XCTestCase { func testErrorHandle() { let json = JSON(data:self.testData) - if let _ = json["wrong-type"].string { + if json["wrong-type"].string != nil { XCTFail("Should not run into here") } else { XCTAssertEqual(json["wrong-type"].error!.code, SwiftyJSON.ErrorWrongType) } - if let _ = json[0]["not-exist"].string { + if json[0]["not-exist"].string != nil { XCTFail("Should not run into here") } else { XCTAssertEqual(json[0]["not-exist"].error!.code, SwiftyJSON.ErrorNotExist) diff --git a/Tests/SwiftyJSONTests/RawRepresentableTests.swift b/Tests/SwiftyJSONTests/RawRepresentableTests.swift index 1482a05b..7a122990 100644 --- a/Tests/SwiftyJSONTests/RawRepresentableTests.swift +++ b/Tests/SwiftyJSONTests/RawRepresentableTests.swift @@ -77,7 +77,7 @@ class RawRepresentableTests: XCTestCase { } func testNil() { - if let _ = JSON(rawValue: NSObject()) { + if JSON(rawValue: NSObject()) != nil { XCTFail("Should not run into here") } } From 06477da6d9b302389f68ff3e35d6863fbdc3cc52 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Sun, 16 Apr 2017 20:00:07 +0800 Subject: [PATCH 152/260] [SwiftLint] Compress swiftlint violations --- Source/SwiftyJSON.swift | 2 +- Tests/SwiftyJSONTests/BaseTests.swift | 5 ++--- Tests/SwiftyJSONTests/PerformanceTests.swift | 9 ++++----- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 01010b39..5f2b7527 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -110,7 +110,7 @@ public struct JSON { @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) - .flatMap{ try? JSON(data: $0) } ?? JSON(NSNull()) + .flatMap { try? JSON(data: $0) } ?? JSON(NSNull()) } /** diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift index aa2524c8..98f6c0c7 100644 --- a/Tests/SwiftyJSONTests/BaseTests.swift +++ b/Tests/SwiftyJSONTests/BaseTests.swift @@ -236,7 +236,7 @@ class BaseTests: XCTestCase { XCTFail("Unable to parse testData") return } - if let _ = json["wrong-type"].string { + if json["wrong-type"].string != nil { XCTFail("Should not run into here") } else { XCTAssertEqual(json["wrong-type"].error!.code, SwiftyJSON.ErrorWrongType) @@ -276,9 +276,8 @@ class BaseTests: XCTestCase { func testErrorThrowing() { let invalidJson = "{\"foo\": 300]" // deliberately incorrect JSON let invalidData = invalidJson.data(using: .utf8)! - do { - let _ = try JSON(data: invalidData) + _ = try JSON(data: invalidData) XCTFail("Should have thrown error; we should not have gotten here") } catch { // everything is OK diff --git a/Tests/SwiftyJSONTests/PerformanceTests.swift b/Tests/SwiftyJSONTests/PerformanceTests.swift index 500c1f6f..72140b54 100644 --- a/Tests/SwiftyJSONTests/PerformanceTests.swift +++ b/Tests/SwiftyJSONTests/PerformanceTests.swift @@ -59,7 +59,7 @@ class PerformanceTests: XCTestCase { XCTFail("Unable to parse testData") return } - self.measure() { + self.measure { for _ in 1...100 { let object:Any? = json.object XCTAssertTrue(object != nil) @@ -72,7 +72,7 @@ class PerformanceTests: XCTestCase { XCTFail("Unable to parse testData") return } - self.measure() { + self.measure { for _ in 1...100 { autoreleasepool { if let array = json.array { @@ -88,8 +88,7 @@ class PerformanceTests: XCTestCase { XCTFail("Unable to parse testData") return } - - self.measure() { + self.measure { for _ in 1...100 { autoreleasepool { if let dictionary = json.dictionary { @@ -105,7 +104,7 @@ class PerformanceTests: XCTestCase { XCTFail("Unable to parse testData") return } - self.measure() { + self.measure { for _ in 1...100 { autoreleasepool { let string = json.rawString() From acbe2412dc58f79fe49b13cdcffceeae49e3bd4f Mon Sep 17 00:00:00 2001 From: JackSteven Date: Thu, 20 Apr 2017 14:51:50 +0800 Subject: [PATCH 153/260] call can throw but is not marked with try Hello, I See JSON(data: data) has throws exception, so add 'try' in front, the error "call can throw but is not marked with try" can fixed. public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { } --- Example/Example/AppDelegate.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Example/Example/AppDelegate.swift b/Example/Example/AppDelegate.swift index f0e91456..4e1880b0 100644 --- a/Example/Example/AppDelegate.swift +++ b/Example/Example/AppDelegate.swift @@ -36,7 +36,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { if let file = Bundle.main.path(forResource: "SwiftyJSONTests", ofType: "json") { do { let data = try Data(contentsOf: URL(fileURLWithPath: file)) - let json = JSON(data: data) + let json = try JSON(data: data) viewController.json = json } catch { viewController.json = JSON.null From 083c6d7c42222846348dd5322ba01186adabf431 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Sat, 22 Apr 2017 15:46:11 +0800 Subject: [PATCH 154/260] Moving from NSError to Swift.Error --- Source/SwiftyJSON.swift | 78 +++++++++++++++++++++++++++++------------ 1 file changed, 55 insertions(+), 23 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 5f2b7527..d79e1c73 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -25,15 +25,54 @@ import Foundation // MARK: - Error ///Error domain +@available(*, deprecated, message: "Use the `SwiftyJSONError.errorDomain` instead") public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code +@available(*, deprecated, message: "Use the `SwiftyJSONError.unsupportedType` instead") public let ErrorUnsupportedType: Int = 999 +@available(*, deprecated, message: "Use the `SwiftyJSONError.indexOutOfBounds` instead") public let ErrorIndexOutOfBounds: Int = 900 +@available(*, deprecated, message: "Use the `SwiftyJSONError.wrongType` instead") public let ErrorWrongType: Int = 901 +@available(*, deprecated, message: "Use the `SwiftyJSONError.notExist` instead") public let ErrorNotExist: Int = 500 +@available(*, deprecated, message: "Use the `SwiftyJSONError.invalidJSON` instead") public let ErrorInvalidJSON: Int = 490 +public enum SwiftyJSONError: Int, Swift.Error { + case unsupportedType = 999 + case indexOutOfBounds = 900 + case elementTooDeep = 902 + case wrongType = 901 + case notExist = 500 + case invalidJSON = 490 +} + +extension SwiftyJSONError: CustomNSError { + + public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" } + + public var errorCode: Int { return self.rawValue } + + public var errorUserInfo: [String : String] { + switch self { + case .unsupportedType: + return [NSLocalizedDescriptionKey: "It is a unsupported type."] + case .indexOutOfBounds: + return [NSLocalizedDescriptionKey: "Array Index is out of bounds."] + case .wrongType: + return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."] + case .notExist: + return [NSLocalizedDescriptionKey: "Dictionary key does not exist."] + case .invalidJSON: + return [NSLocalizedDescriptionKey: "JSON is invalid."] + case .elementTooDeep: + return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."] + } + } +} + // MARK: - JSON Type /** @@ -60,7 +99,6 @@ public struct JSON { - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `[]` by default. - - parameter error: The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ @@ -107,7 +145,7 @@ public struct JSON { - returns: The created JSON */ - @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") + @available(*, deprecated, message: "Use instead `init(parseJSON: )`") public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) .flatMap { try? JSON(data: $0) } ?? JSON(NSNull()) @@ -165,7 +203,7 @@ public struct JSON { } } else { if typecheck { - throw NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]) + throw SwiftyJSONError.wrongType } else { self = other } @@ -182,7 +220,7 @@ public struct JSON { /// Private type fileprivate var _type: Type = .null /// Private error - fileprivate var _error: NSError? + fileprivate var _error: SwiftyJSONError? /// Object in JSON public var object: Any { @@ -228,7 +266,7 @@ public struct JSON { self.rawDictionary = dictionary default: _type = .unknown - _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) + _error = .unsupportedType } } } @@ -237,7 +275,7 @@ public struct JSON { public var type: Type { return _type } /// Error in JSON - public var error: NSError? { return self._error } + public var error: SwiftyJSONError? { return _error } /// The static null JSON @available(*, unavailable, renamed:"null") @@ -378,13 +416,13 @@ extension JSON { get { if self.type != .array { var r = JSON.null - r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) + r._error = self._error ?? SwiftyJSONError.wrongType return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null - r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) + r._error = SwiftyJSONError.indexOutOfBounds return r } } @@ -405,10 +443,10 @@ extension JSON { if let o = self.rawDictionary[key] { r = JSON(o) } else { - r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) + r._error = SwiftyJSONError.notExist } } else { - r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) + r._error = self._error ?? SwiftyJSONError.wrongType } return r } @@ -569,7 +607,7 @@ extension JSON: Swift.RawRepresentable { public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) + throw SwiftyJSONError.invalidJSON } return try JSONSerialization.data(withJSONObject: self.object, options: opt) @@ -595,13 +633,9 @@ extension JSON: Swift.RawRepresentable { } } - fileprivate func _rawString( - _ encoding: String.Encoding = .utf8, - options: [writingOptionsKeys: Any], - maxObjectDepth: Int = 10 - ) throws -> String? { + fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { if maxObjectDepth < 0 { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop"]) + throw SwiftyJSONError.invalidJSON } switch self.type { case .dictionary: @@ -625,7 +659,7 @@ extension JSON: Swift.RawRepresentable { let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) + throw SwiftyJSONError.elementTooDeep } if nestedValue.type == .string { return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" @@ -656,7 +690,7 @@ extension JSON: Swift.RawRepresentable { let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { - throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) + throw SwiftyJSONError.invalidJSON } if nestedValue.type == .string { return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" @@ -930,10 +964,8 @@ extension JSON { } } public func exists() -> Bool { - if let errorValue = error, errorValue.code == ErrorNotExist || - errorValue.code == ErrorIndexOutOfBounds || - errorValue.code == ErrorWrongType { - return false + if let errorValue = error, (400...1000).contains(errorValue.errorCode) { + return false } return true } From d3ae7a1bd16bac12fb81c6ddb1503311335fe9eb Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Sat, 22 Apr 2017 15:47:26 +0800 Subject: [PATCH 155/260] Fix failure testcases --- Source/SwiftyJSON.swift | 2 +- Tests/SwiftyJSONTests/BaseTests.swift | 6 ++-- Tests/SwiftyJSONTests/MergeTests.swift | 12 +++---- Tests/SwiftyJSONTests/RawTests.swift | 6 ++-- Tests/SwiftyJSONTests/SubscriptTests.swift | 38 +++++++++++----------- 5 files changed, 31 insertions(+), 33 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index d79e1c73..3243cfd1 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -55,7 +55,7 @@ extension SwiftyJSONError: CustomNSError { public var errorCode: Int { return self.rawValue } - public var errorUserInfo: [String : String] { + public var errorUserInfo: [String : Any] { switch self { case .unsupportedType: return [NSLocalizedDescriptionKey: "It is a unsupported type."] diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift index 98f6c0c7..616ea020 100644 --- a/Tests/SwiftyJSONTests/BaseTests.swift +++ b/Tests/SwiftyJSONTests/BaseTests.swift @@ -239,18 +239,18 @@ class BaseTests: XCTestCase { if json["wrong-type"].string != nil { XCTFail("Should not run into here") } else { - XCTAssertEqual(json["wrong-type"].error!.code, SwiftyJSON.ErrorWrongType) + XCTAssertEqual(json["wrong-type"].error, SwiftyJSONError.wrongType) } if json[0]["not-exist"].string != nil { XCTFail("Should not run into here") } else { - XCTAssertEqual(json[0]["not-exist"].error!.code, SwiftyJSON.ErrorNotExist) + XCTAssertEqual(json[0]["not-exist"].error, SwiftyJSONError.notExist) } let wrongJSON = JSON(NSObject()) if let error = wrongJSON.error { - XCTAssertEqual(error.code, SwiftyJSON.ErrorUnsupportedType) + XCTAssertEqual(error, SwiftyJSONError.unsupportedType) } } diff --git a/Tests/SwiftyJSONTests/MergeTests.swift b/Tests/SwiftyJSONTests/MergeTests.swift index dbee6a35..4d1d8c09 100644 --- a/Tests/SwiftyJSONTests/MergeTests.swift +++ b/Tests/SwiftyJSONTests/MergeTests.swift @@ -33,13 +33,11 @@ class JSONTests: XCTestCase { do { _ = try A.merged(with: B) XCTFail() - } catch (let error) { - let error = error as NSError - XCTAssertEqual(error.code, ErrorWrongType) - XCTAssertEqual(error.domain, ErrorDomain) - XCTAssertEqual(error.userInfo[NSLocalizedDescriptionKey] as! String, - "Couldn't merge, because the JSONs differ in type on top level.") - } + } catch let error as SwiftyJSONError { + XCTAssertEqual(error.errorCode, SwiftyJSONError.wrongType.rawValue) + XCTAssertEqual(type(of: error).errorDomain, SwiftyJSONError.errorDomain) + XCTAssertEqual(error.errorUserInfo as! [String: String], [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]) + } catch _ {} } func testPrimitiveType() { diff --git a/Tests/SwiftyJSONTests/RawTests.swift b/Tests/SwiftyJSONTests/RawTests.swift index e30de39d..b104e1c5 100644 --- a/Tests/SwiftyJSONTests/RawTests.swift +++ b/Tests/SwiftyJSONTests/RawTests.swift @@ -40,9 +40,9 @@ class RawTests: XCTestCase { let json: JSON = "...xyz" do { _ = try json.rawData() - } catch let error as NSError { - XCTAssertEqual(error.code, ErrorInvalidJSON) - } + } catch let error as SwiftyJSONError { + XCTAssertEqual(error, SwiftyJSONError.invalidJSON) + } catch _ {} } func testArray() { diff --git a/Tests/SwiftyJSONTests/SubscriptTests.swift b/Tests/SwiftyJSONTests/SubscriptTests.swift index 7c71a941..78e6c075 100644 --- a/Tests/SwiftyJSONTests/SubscriptTests.swift +++ b/Tests/SwiftyJSONTests/SubscriptTests.swift @@ -180,37 +180,37 @@ class SubscriptTests: XCTestCase { func testOutOfBounds() { let json: JSON = JSON ([[NSNumber(value:1), NSNumber(value:2.123456), NSNumber(value:123456789)], ["aa", "bbb", "cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) XCTAssertEqual(json[9], JSON.null) - XCTAssertEqual(json[-2].error!.code, ErrorIndexOutOfBounds) - XCTAssertEqual(json[6].error!.code, ErrorIndexOutOfBounds) + XCTAssertEqual(json[-2].error, SwiftyJSONError.indexOutOfBounds) + XCTAssertEqual(json[6].error, SwiftyJSONError.indexOutOfBounds) XCTAssertEqual(json[9][8], JSON.null) - XCTAssertEqual(json[8][7].error!.code, ErrorIndexOutOfBounds) - XCTAssertEqual(json[8, 7].error!.code, ErrorIndexOutOfBounds) - XCTAssertEqual(json[999].error!.code, ErrorIndexOutOfBounds) + XCTAssertEqual(json[8][7].error, SwiftyJSONError.indexOutOfBounds) + XCTAssertEqual(json[8, 7].error, SwiftyJSONError.indexOutOfBounds) + XCTAssertEqual(json[999].error, SwiftyJSONError.indexOutOfBounds) } func testErrorWrongType() { let json = JSON(12345) XCTAssertEqual(json[9], JSON.null) - XCTAssertEqual(json[9].error!.code, ErrorWrongType) - XCTAssertEqual(json[8][7].error!.code, ErrorWrongType) + XCTAssertEqual(json[9].error, SwiftyJSONError.wrongType) + XCTAssertEqual(json[8][7].error, SwiftyJSONError.wrongType) XCTAssertEqual(json["name"], JSON.null) - XCTAssertEqual(json["name"].error!.code, ErrorWrongType) - XCTAssertEqual(json[0]["name"].error!.code, ErrorWrongType) - XCTAssertEqual(json["type"]["name"].error!.code, ErrorWrongType) - XCTAssertEqual(json["name"][99].error!.code, ErrorWrongType) - XCTAssertEqual(json[1, "Value"].error!.code, ErrorWrongType) - XCTAssertEqual(json[1, 2, "Value"].error!.code, ErrorWrongType) - XCTAssertEqual(json[[1, 2, "Value"]].error!.code, ErrorWrongType) + XCTAssertEqual(json["name"].error, SwiftyJSONError.wrongType) + XCTAssertEqual(json[0]["name"].error, SwiftyJSONError.wrongType) + XCTAssertEqual(json["type"]["name"].error, SwiftyJSONError.wrongType) + XCTAssertEqual(json["name"][99].error, SwiftyJSONError.wrongType) + XCTAssertEqual(json[1, "Value"].error, SwiftyJSONError.wrongType) + XCTAssertEqual(json[1, 2, "Value"].error, SwiftyJSONError.wrongType) + XCTAssertEqual(json[[1, 2, "Value"]].error, SwiftyJSONError.wrongType) } func testErrorNotExist() { let json: JSON = ["name": "NAME", "age": 15] XCTAssertEqual(json["Type"], JSON.null) - XCTAssertEqual(json["Type"].error!.code, ErrorNotExist) - XCTAssertEqual(json["Type"][1].error!.code, ErrorNotExist) - XCTAssertEqual(json["Type", 1].error!.code, ErrorNotExist) - XCTAssertEqual(json["Type"]["Value"].error!.code, ErrorNotExist) - XCTAssertEqual(json["Type", "Value"].error!.code, ErrorNotExist) + XCTAssertEqual(json["Type"].error, SwiftyJSONError.notExist) + XCTAssertEqual(json["Type"][1].error, SwiftyJSONError.notExist) + XCTAssertEqual(json["Type", 1].error, SwiftyJSONError.notExist) + XCTAssertEqual(json["Type"]["Value"].error, SwiftyJSONError.notExist) + XCTAssertEqual(json["Type", "Value"].error, SwiftyJSONError.notExist) } func testMultilevelGetter() { From 0bf454603f31554a66e0cabb28d1d03eb8fd754c Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 3 May 2017 22:15:59 +0800 Subject: [PATCH 156/260] Added SwiftyJSONError namespace --- Source/SwiftyJSON.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 3243cfd1..9e5e358d 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -266,7 +266,7 @@ public struct JSON { self.rawDictionary = dictionary default: _type = .unknown - _error = .unsupportedType + _error = SwiftyJSONError.unsupportedType } } } From 74c3f1c96aadaa597b42bfd108eb02d0af409434 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 3 May 2017 22:29:13 +0800 Subject: [PATCH 157/260] Update README.md --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6c462346..3dd74189 100644 --- a/README.md +++ b/README.md @@ -213,11 +213,18 @@ for (index,subJson):(String, JSON) in json { #### Error +##### SwiftyJSON 4.x + +SwiftyJSON 4.x introduces an enum type called `SwiftyJSONError`, which includes `unsupportedType`, `indexOutOfBounds`, `elementTooDeep`, `wrongType`, `notExist` and `invalidJSON`, at the same time, `ErrorDomain` are being replaced by `SwiftyJSONError.errorDomain`. +Note: Those old error types are deprecated in SwiftyJSON 4.x and will be removed in the future release. + +##### SwiftyJSON 3.x + Use a subscript to get/set a value in an Array or Dictionary If the JSON is: * an array, the app may crash with "index out-of-bounds." -* a dictionary, it will be assigned `nil` without a reason. +* a dictionary, it will be assigned to `nil` without a reason. * not an array or a dictionary, the app may crash with an "unrecognised selector" exception. This will never happen in SwiftyJSON. From f261e70e942404ed6675f83b35799b884d42ad06 Mon Sep 17 00:00:00 2001 From: Nonchalant Date: Wed, 17 May 2017 20:34:47 +0900 Subject: [PATCH 158/260] Fix comma-spacing on version string. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3dd74189..814f68c9 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ let package = Package( name: "YOUR_PROJECT_NAME", targets: [], dependencies: [ - .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1,0,0).. Date: Thu, 25 May 2017 15:26:46 +1200 Subject: [PATCH 159/260] =?UTF-8?q?Declare=20JSON=E2=80=99s=20type=20and?= =?UTF-8?q?=20error=20in=20a=20concise=20way.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Source/SwiftyJSON.swift | 44 +++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 9e5e358d..a0121c99 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -217,10 +217,12 @@ public struct JSON { fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() fileprivate var rawBool: Bool = false - /// Private type - fileprivate var _type: Type = .null - /// Private error - fileprivate var _error: SwiftyJSONError? + + /// JSON type, fileprivate setter + public fileprivate(set) var type: Type = .null + + /// Error in JSON, fileprivate setter + public fileprivate(set) var error: SwiftyJSONError? /// Object in JSON public var object: Any { @@ -241,42 +243,36 @@ public struct JSON { } } set { - _error = nil + error = nil switch unwrap(newValue) { case let number as NSNumber: if number.isBool { - _type = .bool + type = .bool self.rawBool = number.boolValue } else { - _type = .number + type = .number self.rawNumber = number } case let string as String: - _type = .string + type = .string self.rawString = string case _ as NSNull: - _type = .null + type = .null case nil: - _type = .null + type = .null case let array as [Any]: - _type = .array + type = .array self.rawArray = array case let dictionary as [String : Any]: - _type = .dictionary + type = .dictionary self.rawDictionary = dictionary default: - _type = .unknown - _error = SwiftyJSONError.unsupportedType + type = .unknown + error = SwiftyJSONError.unsupportedType } } } - /// JSON type - public var type: Type { return _type } - - /// Error in JSON - public var error: SwiftyJSONError? { return _error } - /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { return null } @@ -416,13 +412,13 @@ extension JSON { get { if self.type != .array { var r = JSON.null - r._error = self._error ?? SwiftyJSONError.wrongType + r.error = self.error ?? SwiftyJSONError.wrongType return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null - r._error = SwiftyJSONError.indexOutOfBounds + r.error = SwiftyJSONError.indexOutOfBounds return r } } @@ -443,10 +439,10 @@ extension JSON { if let o = self.rawDictionary[key] { r = JSON(o) } else { - r._error = SwiftyJSONError.notExist + r.error = SwiftyJSONError.notExist } } else { - r._error = self._error ?? SwiftyJSONError.wrongType + r.error = self.error ?? SwiftyJSONError.wrongType } return r } From ddfb135d5f043907db534a5c49590139d4aba531 Mon Sep 17 00:00:00 2001 From: Matthew An Date: Thu, 25 May 2017 15:53:02 +1200 Subject: [PATCH 160/260] Get rid of trailing whitespaces --- Source/SwiftyJSON.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index a0121c99..f4815aae 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -217,10 +217,10 @@ public struct JSON { fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() fileprivate var rawBool: Bool = false - + /// JSON type, fileprivate setter public fileprivate(set) var type: Type = .null - + /// Error in JSON, fileprivate setter public fileprivate(set) var error: SwiftyJSONError? From 236aabb0a18c0b9a1084e9b6dce00cffc99c3d45 Mon Sep 17 00:00:00 2001 From: Matthew An Date: Fri, 2 Jun 2017 09:15:37 +1200 Subject: [PATCH 161/260] Fix three typos --- Source/SwiftyJSON.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 9e5e358d..86b808a4 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -58,7 +58,7 @@ extension SwiftyJSONError: CustomNSError { public var errorUserInfo: [String : Any] { switch self { case .unsupportedType: - return [NSLocalizedDescriptionKey: "It is a unsupported type."] + return [NSLocalizedDescriptionKey: "It is an unsupported type."] case .indexOutOfBounds: return [NSLocalizedDescriptionKey: "Array Index is out of bounds."] case .wrongType: @@ -411,7 +411,7 @@ extension String: JSONSubscriptType { extension JSON { - /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. + /// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { if self.type != .array { @@ -435,7 +435,7 @@ extension JSON { } } - /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. + /// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null From e9c12fafcb58454518f432a6f6c4a915a0a11762 Mon Sep 17 00:00:00 2001 From: Matthew An Date: Fri, 2 Jun 2017 09:24:14 +1200 Subject: [PATCH 162/260] =?UTF-8?q?Fix=20a=20potential=20crash=20issue=20b?= =?UTF-8?q?y=20checking=20whether=20index=20is=20out=20of=20json=20array?= =?UTF-8?q?=E2=80=99s=20bound.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Source/SwiftyJSON.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 86b808a4..ce41d5f5 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -418,7 +418,7 @@ extension JSON { var r = JSON.null r._error = self._error ?? SwiftyJSONError.wrongType return r - } else if index >= 0 && index < self.rawArray.count { + } else if self.rawArray.indices.contains(index) { return JSON(self.rawArray[index]) } else { var r = JSON.null @@ -427,10 +427,10 @@ extension JSON { } } set { - if self.type == .array { - if self.rawArray.count > index && newValue.error == nil { - self.rawArray[index] = newValue.object - } + if self.type == .array && + self.rawArray.indices.contains(index) && + newValue.error == nil { + self.rawArray[index] = newValue.object } } } From a4a099b6eeeb43541bbee205ebb35816be77ec4d Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Fri, 26 May 2017 11:06:54 +0800 Subject: [PATCH 163/260] =?UTF-8?q?Change=20NSNumber=20extension=E2=80=99s?= =?UTF-8?q?=20property=20to=20fileprivate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Source/SwiftyJSON.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 30cbb5d0..2a1b6b73 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -1358,7 +1358,7 @@ private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { - var isBool: Bool { + fileprivate var isBool: Bool { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { return true From ebc305b69ecca005b636f20e0db4d07d19d333fa Mon Sep 17 00:00:00 2001 From: Jeff Gu Kang Date: Sun, 4 Jun 2017 23:40:09 +0900 Subject: [PATCH 164/260] Update examples that makes warning in README `.error` to `error!`. --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 814f68c9..53f4df97 100644 --- a/README.md +++ b/README.md @@ -234,7 +234,7 @@ let json = JSON(["name", "age"]) if let name = json[999].string { //Do something you want } else { - print(json[999].error) // "Array[999] is out of bounds" + print(json[999].error!) // "Array[999] is out of bounds" } ``` @@ -243,7 +243,7 @@ let json = JSON(["name":"Jack", "age": 25]) if let name = json["address"].string { //Do something you want } else { - print(json["address"].error) // "Dictionary["address"] does not exist" + print(json["address"].error!) // "Dictionary["address"] does not exist" } ``` @@ -253,14 +253,14 @@ if let age = json[0].string { //Do something you want } else { print(json[0]) // "Array[0] failure, It is not an array" - print(json[0].error) // "Array[0] failure, It is not an array" + print(json[0].error!) // "Array[0] failure, It is not an array" } if let name = json["name"].string { //Do something you want } else { print(json["name"]) // "Dictionary[\"name"] failure, It is not an dictionary" - print(json["name"].error) // "Dictionary[\"name"] failure, It is not an dictionary" + print(json["name"].error!) // "Dictionary[\"name"] failure, It is not an dictionary" } ``` @@ -272,7 +272,7 @@ if let id = json["user"]["favourites_count"].number { //Do something you want } else { //Print the error - print(json["user"]["favourites_count"].error) + print(json["user"]["favourites_count"].error!) } ``` @@ -282,7 +282,7 @@ if let id = json["user"]["name"].string { //Do something you want } else { //Print the error - print(json["user"]["name"]) + print(json["user"]["name"].error!) } ``` @@ -292,7 +292,7 @@ if let id = json["user"]["is_translator"].bool { //Do something you want } else { //Print the error - print(json["user"]["is_translator"]) + print(json["user"]["is_translator"].error!) } ``` @@ -302,7 +302,7 @@ if let id = json["user"]["id"].int { //Do something you want } else { //Print the error - print(json["user"]["id"]) + print(json["user"]["id"].error!) } ... ``` From 2f0d8283612580dd4ce7242c5e13b59a3f8fe1a1 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 15 Aug 2017 11:13:07 +0800 Subject: [PATCH 165/260] [Swift4] Update System recommend settings --- Example/Example.xcodeproj/project.pbxproj | 14 ++++++++- SwiftyJSON.xcodeproj/project.pbxproj | 31 ++++++++++++++----- .../xcschemes/SwiftyJSON OSX.xcscheme | 4 ++- .../xcschemes/SwiftyJSON iOS.xcscheme | 4 ++- .../xcschemes/SwiftyJSON tvOS.xcscheme | 4 ++- .../xcschemes/SwiftyJSON watchOS.xcscheme | 4 ++- 6 files changed, 49 insertions(+), 12 deletions(-) diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index b114ac1e..9abea6d6 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -124,7 +124,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0700; - LastUpgradeCheck = 0800; + LastUpgradeCheck = 0900; ORGANIZATIONNAME = swiftyjson; TargetAttributes = { A82A1C1819D926B8009A653D = { @@ -206,14 +206,20 @@ CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; @@ -254,14 +260,20 @@ CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 1ebccd13..500d12e8 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -452,16 +452,16 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0710; - LastUpgradeCheck = 0820; + LastUpgradeCheck = 0900; TargetAttributes = { 2E4FEFDA19575BE100351305 = { CreatedOnToolsVersion = 6.0; - LastSwiftMigration = 0820; + LastSwiftMigration = 0900; ProvisioningStyle = Automatic; }; 2E4FEFE519575BE100351305 = { CreatedOnToolsVersion = 6.0; - LastSwiftMigration = 0820; + LastSwiftMigration = 0900; ProvisioningStyle = Manual; TestTargetID = 2E4FEFDA19575BE100351305; }; @@ -713,14 +713,20 @@ CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; @@ -765,14 +771,20 @@ CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; @@ -823,7 +835,8 @@ PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 3.0; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; }; name = Debug; }; @@ -846,7 +859,8 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; - SWIFT_VERSION = 3.0; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; }; name = Release; }; @@ -867,7 +881,8 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 3.0; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; }; name = Debug; }; @@ -883,7 +898,8 @@ METAL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 3.0; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; }; name = Release; }; @@ -1201,6 +1217,7 @@ A81D162D1E5743B000C62C5F /* Release */, ); defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; }; A8580F7C1BCF5C5B00DA927B /* Build configuration list for PBXNativeTarget "SwiftyJSON tvOS Tests" */ = { isa = XCConfigurationList; diff --git a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme index 33f6b13c..12940bae 100644 --- a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme +++ b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme @@ -1,6 +1,6 @@ @@ -36,6 +37,7 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + language = "" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" From 14147406199b38473f50bf2a21cf9482b3576deb Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Mon, 26 Jun 2017 12:17:14 +0800 Subject: [PATCH 166/260] Add detail about deprecated method --- Source/SwiftyJSON.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 2a1b6b73..75cfe3a7 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -25,19 +25,19 @@ import Foundation // MARK: - Error ///Error domain -@available(*, deprecated, message: "Use the `SwiftyJSONError.errorDomain` instead") +@available(*, deprecated, message: "ErrorDomain is deprecated. Use `SwiftyJSONError.errorDomain` instead.", renamed: "SwiftyJSONError.errorDomain") public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code -@available(*, deprecated, message: "Use the `SwiftyJSONError.unsupportedType` instead") +@available(*, deprecated, message: "ErrorUnsupportedType is deprecated. Use `SwiftyJSONError.ErrorUnsupportedType` instead.", renamed: "SwiftyJSONError.ErrorUnsupportedType") public let ErrorUnsupportedType: Int = 999 -@available(*, deprecated, message: "Use the `SwiftyJSONError.indexOutOfBounds` instead") +@available(*, deprecated, message: "ErrorIndexOutOfBounds is deprecated. Use `SwiftyJSONError.ErrorIndexOutOfBounds` instead.", renamed: "SwiftyJSONError.ErrorIndexOutOfBounds") public let ErrorIndexOutOfBounds: Int = 900 -@available(*, deprecated, message: "Use the `SwiftyJSONError.wrongType` instead") +@available(*, deprecated, message: "ErrorWrongType is deprecated. Use `SwiftyJSONError.ErrorWrongType` instead.", renamed: "SwiftyJSONError.ErrorWrongType") public let ErrorWrongType: Int = 901 -@available(*, deprecated, message: "Use the `SwiftyJSONError.notExist` instead") +@available(*, deprecated, message: "ErrorNotExist is deprecated. Use `SwiftyJSONError.ErrorNotExist` instead.", renamed: "SwiftyJSONError.ErrorNotExist") public let ErrorNotExist: Int = 500 -@available(*, deprecated, message: "Use the `SwiftyJSONError.invalidJSON` instead") +@available(*, deprecated, message: "ErrorInvalidJSON is deprecated. Use `SwiftyJSONError.ErrorInvalidJSON` instead.", renamed: "SwiftyJSONError.ErrorInvalidJSON") public let ErrorInvalidJSON: Int = 490 public enum SwiftyJSONError: Int, Swift.Error { From 7b02c2b5be2d43dfb2d4f24efd63067dc1c8f1b5 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 15 Aug 2017 11:15:51 +0800 Subject: [PATCH 167/260] [Travis] Update osx_image to Xcode8.3 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 63840195..50334d9b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: objective-c -osx_image: xcode8 +osx_image: xcode8.3 xcode_sdk: iphonesimulator10.0 env: global: From 52ff87909072f56e55017e90d3c3e8ee7ea2ef2a Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 15 Aug 2017 11:27:07 +0800 Subject: [PATCH 168/260] [Travis] Use stable version over head version --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 50334d9b..d6f1d9dc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,7 @@ env: global: - FRAMEWORK_NAME=SwiftyJSON before_install: -- rvm get head +- rvm get stable - brew update - brew outdated carthage || brew upgrade carthage before_deploy: From b5453968803e80785f7faae78b3fe56bb061f67e Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 15 Aug 2017 11:42:32 +0800 Subject: [PATCH 169/260] [Gardening] Fix TravisCI --- .travis.yml | 19 ------------------- Source/SwiftyJSON.swift | 2 +- 2 files changed, 1 insertion(+), 20 deletions(-) diff --git a/.travis.yml b/.travis.yml index d6f1d9dc..796a8a00 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,27 +1,8 @@ language: objective-c osx_image: xcode8.3 xcode_sdk: iphonesimulator10.0 -env: - global: - - FRAMEWORK_NAME=SwiftyJSON -before_install: -- rvm get stable -- brew update -- brew outdated carthage || brew upgrade carthage -before_deploy: -- carthage build --no-skip-current -- carthage archive $FRAMEWORK_NAME script: - set -o pipefail - travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON iOS" -destination "platform=iOS Simulator,name=iPhone 6" build-for-testing test | xcpretty - travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON OSX" build-for-testing test | xcpretty - travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON tvOS" -destination "platform=tvOS Simulator,name=Apple TV 1080p" build-for-testing test | xcpretty -deploy: - provider: releases - api_key: - secure: MufQRIzcHPU5fn9gyXl7kDGaLihN6zGABx9UWqNtkwq0AxV0aYNWys11nrKDIgoZFR+MbQHMoodpZK03yDdCLG03ncnOr3aytLOpI0imuDFWx16sieiVoYmnP5bfNFTN0qqXdfBy0OOsx4wO+F5Pwg5y1TgGYnKpXtEfdIU3Om4= - file: SwiftyJSON.framework.zip - skip_cleanup: true - on: - repo: SwiftyJSON/SwiftyJSON - tags: true diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 75cfe3a7..72cbc96b 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -23,7 +23,7 @@ import Foundation // MARK: - Error - +// swiftlint:disable line_length ///Error domain @available(*, deprecated, message: "ErrorDomain is deprecated. Use `SwiftyJSONError.errorDomain` instead.", renamed: "SwiftyJSONError.errorDomain") public let ErrorDomain: String = "SwiftyJSONErrorDomain" From 1e99c7b7383ad107ad17d4300e43264395ea2529 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 15 Aug 2017 12:24:42 +0800 Subject: [PATCH 170/260] Address #870 --- Tests/SwiftyJSONTests/MutabilityTests.swift | 38 +++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/Tests/SwiftyJSONTests/MutabilityTests.swift b/Tests/SwiftyJSONTests/MutabilityTests.swift index 6a48cf79..c02a7b0c 100644 --- a/Tests/SwiftyJSONTests/MutabilityTests.swift +++ b/Tests/SwiftyJSONTests/MutabilityTests.swift @@ -25,7 +25,7 @@ import SwiftyJSON class MutabilityTest: XCTestCase { - func testDictionaryJSONMutability() { + func testDictionaryMutability() { let dictionary: [String: Any] = [ "string": "STRING", "number": 9823.212, @@ -55,7 +55,7 @@ class MutabilityTest: XCTestCase { XCTAssertEqual(json["new"], ["foo": "bar"]) } - func testArrayJSONMutability() { + func testArrayMutability() { let array: [Any] = ["1", "2", 3, true, []] var json = JSON(array) @@ -103,4 +103,38 @@ class MutabilityTest: XCTestCase { XCTAssertEqual(boolean, false) XCTAssertEqual(boolean.boolValue, false) } + + func testArrayRemovability() { + let array = ["Test", "Test2", "Test3"] + var json = JSON(array) + + json.arrayObject?.removeFirst() + XCTAssertEqual(false, json.arrayValue.isEmpty) + XCTAssertEqual(json.arrayValue, ["Test2", "Test3"]) + + json.arrayObject?.removeLast() + XCTAssertEqual(false, json.arrayValue.isEmpty) + XCTAssertEqual(json.arrayValue, ["Test2"]) + + json.arrayObject?.removeAll() + XCTAssertEqual(true, json.arrayValue.isEmpty) + XCTAssertEqual(JSON([]), json) + } + + func testDictionaryRemovability() { + let dictionary: [String : Any] = ["key1": "Value1", "key2": 2, "key3": true] + var json = JSON(dictionary) + + json.dictionaryObject?.removeValue(forKey: "key1") + XCTAssertEqual(false, json.dictionaryValue.isEmpty) + XCTAssertEqual(json.dictionaryValue, ["key2": 2, "key3": true]) + + json.dictionaryObject?.removeValue(forKey: "key3") + XCTAssertEqual(false, json.dictionaryValue.isEmpty) + XCTAssertEqual(json.dictionaryValue, ["key2": 2]) + + json.dictionaryObject?.removeAll() + XCTAssertEqual(true, json.dictionaryValue.isEmpty) + XCTAssertEqual(json.dictionaryValue, [:]) + } } From e9e53b8076e3cc8eabcb6ea53d70395b136dad5e Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 15 Aug 2017 12:28:51 +0800 Subject: [PATCH 171/260] Compress SwiftLint violations --- Tests/SwiftyJSONTests/MutabilityTests.swift | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Tests/SwiftyJSONTests/MutabilityTests.swift b/Tests/SwiftyJSONTests/MutabilityTests.swift index c02a7b0c..bf0b786b 100644 --- a/Tests/SwiftyJSONTests/MutabilityTests.swift +++ b/Tests/SwiftyJSONTests/MutabilityTests.swift @@ -103,36 +103,36 @@ class MutabilityTest: XCTestCase { XCTAssertEqual(boolean, false) XCTAssertEqual(boolean.boolValue, false) } - + func testArrayRemovability() { let array = ["Test", "Test2", "Test3"] var json = JSON(array) - + json.arrayObject?.removeFirst() XCTAssertEqual(false, json.arrayValue.isEmpty) XCTAssertEqual(json.arrayValue, ["Test2", "Test3"]) - + json.arrayObject?.removeLast() XCTAssertEqual(false, json.arrayValue.isEmpty) XCTAssertEqual(json.arrayValue, ["Test2"]) - + json.arrayObject?.removeAll() XCTAssertEqual(true, json.arrayValue.isEmpty) XCTAssertEqual(JSON([]), json) } - + func testDictionaryRemovability() { let dictionary: [String : Any] = ["key1": "Value1", "key2": 2, "key3": true] var json = JSON(dictionary) - + json.dictionaryObject?.removeValue(forKey: "key1") XCTAssertEqual(false, json.dictionaryValue.isEmpty) XCTAssertEqual(json.dictionaryValue, ["key2": 2, "key3": true]) - + json.dictionaryObject?.removeValue(forKey: "key3") XCTAssertEqual(false, json.dictionaryValue.isEmpty) XCTAssertEqual(json.dictionaryValue, ["key2": 2]) - + json.dictionaryObject?.removeAll() XCTAssertEqual(true, json.dictionaryValue.isEmpty) XCTAssertEqual(json.dictionaryValue, [:]) From 522575b5cd291bdc574e9c247f78e65a620d341c Mon Sep 17 00:00:00 2001 From: Abdullah Tawfik Date: Tue, 22 Aug 2017 01:13:32 +0300 Subject: [PATCH 172/260] Tiny optimization --- Example/Example/ViewController.swift | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index 12a05290..1c584824 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -30,16 +30,12 @@ class ViewController: UITableViewController { // MARK: - Table view data source override func viewDidLoad() { - self.title = "SwiftyJSON(\(json.type))" + title = "SwiftyJSON(\(json.type))" } - override func numberOfSections(in tableView: UITableView) -> Int { - return 1 - } - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch self.json.type { - case Type.array, Type.dictionary: + case .array, .dictionary: return self.json.count default: return 1 @@ -49,7 +45,7 @@ class ViewController: UITableViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "JSONCell", for: indexPath) as UITableViewCell - let row = (indexPath as NSIndexPath).row + let row = indexPath.row switch self.json.type { case .array: @@ -76,7 +72,7 @@ class ViewController: UITableViewController { nextController = segue.destination if let indexPath = self.tableView.indexPathForSelectedRow { - let row = (indexPath as NSIndexPath).row + let row = indexPath.row var nextJson: JSON = JSON.null switch self.json.type { case .array: From 7ffd87c4918df2c410ba76717ac88915ab030307 Mon Sep 17 00:00:00 2001 From: Jeff Gu Kang Date: Fri, 18 Aug 2017 17:37:29 +0900 Subject: [PATCH 173/260] Fix wrong descriptions and renamed in deprecated error code --- Source/SwiftyJSON.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 72cbc96b..8e085e7f 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -29,15 +29,15 @@ import Foundation public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code -@available(*, deprecated, message: "ErrorUnsupportedType is deprecated. Use `SwiftyJSONError.ErrorUnsupportedType` instead.", renamed: "SwiftyJSONError.ErrorUnsupportedType") +@available(*, deprecated, message: "ErrorUnsupportedType is deprecated. Use `SwiftyJSONError.unsupportedType` instead.", renamed: "SwiftyJSONError.unsupportedType") public let ErrorUnsupportedType: Int = 999 -@available(*, deprecated, message: "ErrorIndexOutOfBounds is deprecated. Use `SwiftyJSONError.ErrorIndexOutOfBounds` instead.", renamed: "SwiftyJSONError.ErrorIndexOutOfBounds") +@available(*, deprecated, message: "ErrorIndexOutOfBounds is deprecated. Use `SwiftyJSONError.indexOutOfBounds` instead.", renamed: "SwiftyJSONError.indexOutOfBounds") public let ErrorIndexOutOfBounds: Int = 900 -@available(*, deprecated, message: "ErrorWrongType is deprecated. Use `SwiftyJSONError.ErrorWrongType` instead.", renamed: "SwiftyJSONError.ErrorWrongType") +@available(*, deprecated, message: "ErrorWrongType is deprecated. Use `SwiftyJSONError.wrongType` instead.", renamed: "SwiftyJSONError.wrongType") public let ErrorWrongType: Int = 901 -@available(*, deprecated, message: "ErrorNotExist is deprecated. Use `SwiftyJSONError.ErrorNotExist` instead.", renamed: "SwiftyJSONError.ErrorNotExist") +@available(*, deprecated, message: "ErrorNotExist is deprecated. Use `SwiftyJSONError.notExist` instead.", renamed: "SwiftyJSONError.notExist") public let ErrorNotExist: Int = 500 -@available(*, deprecated, message: "ErrorInvalidJSON is deprecated. Use `SwiftyJSONError.ErrorInvalidJSON` instead.", renamed: "SwiftyJSONError.ErrorInvalidJSON") +@available(*, deprecated, message: "ErrorInvalidJSON is deprecated. Use `SwiftyJSONError.invalidJSON` instead.", renamed: "SwiftyJSONError.invalidJSON") public let ErrorInvalidJSON: Int = 490 public enum SwiftyJSONError: Int, Swift.Error { From fffe564b0d8e729bf95dc0f100ff221092c4c4b5 Mon Sep 17 00:00:00 2001 From: Jeff Gu Kang Date: Fri, 18 Aug 2017 19:34:16 +0900 Subject: [PATCH 174/260] Update comments by same rule of markup for formatting quick help --- Source/SwiftyJSON.swift | 164 +++++++++++++++++++++------------------- 1 file changed, 88 insertions(+), 76 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 8e085e7f..3b20706b 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -76,43 +76,45 @@ extension SwiftyJSONError: CustomNSError { // MARK: - JSON Type /** - JSON's type definitions. +JSON's type definitions. - See http://www.json.org - */ +See http://www.json.org +*/ public enum Type: Int { - - case number - case string - case bool - case array - case dictionary - case null - case unknown + + case number + case string + case bool + case array + case dictionary + case null + case unknown } // MARK: - JSON Base public struct JSON { - /** - Creates a JSON using the data. - - - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - - parameter opt: The JSON serialization reading options. `[]` by default. - - - returns: The created JSON - */ + /** + Creates a JSON using the data. + + - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary + - parameter opt: The JSON serialization reading options. `[]` by default. + + - returns: The created JSON + */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(jsonObject: object) } /** - Creates a JSON object - - parameter object: the object - - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - - returns: the created JSON object - */ + Creates a JSON object + - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` + + - parameter object: the object + + - returns: the created JSON object + */ public init(_ object: Any) { switch object { case let object as Data: @@ -126,61 +128,67 @@ public struct JSON { } } - /** - Parses the JSON string into a JSON object - - parameter json: the JSON string - - returns: the created JSON object - */ - public init(parseJSON jsonString: String) { - if let data = jsonString.data(using: .utf8) { - self.init(data) - } else { - self.init(NSNull()) - } - } - - /** - Creates a JSON from JSON string - - parameter string: Normal json string like '{"a":"b"}' + /** + Parses the JSON string into a JSON object + + - parameter json: the JSON string + + - returns: the created JSON object + */ + public init(parseJSON jsonString: String) { + if let data = jsonString.data(using: .utf8) { + self.init(data) + } else { + self.init(NSNull()) + } + } - - returns: The created JSON - */ + /** + Creates a JSON from JSON string + + - parameter json: Normal json string like '{"a":"b"}' + + - returns: The created JSON + */ @available(*, deprecated, message: "Use instead `init(parseJSON: )`") public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) .flatMap { try? JSON(data: $0) } ?? JSON(NSNull()) } - /** - Creates a JSON using the object. - - - 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. - - - returns: The created JSON - */ + /** + Creates a JSON using the object. + + - parameter jsonObject: 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. + + - returns: The created JSON + */ fileprivate init(jsonObject: Any) { self.object = jsonObject } - /** - Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, - present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. + /** + Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - - parameter other: The JSON which gets merged into this JSON - - throws `ErrorWrongType` if the other JSONs differs in type on the top level. - */ + - parameter other: The JSON which gets merged into this JSON + + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. + */ public mutating func merge(with other: JSON) throws { try self.merge(with: other, typecheck: true) } - /** - Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, - present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - - - parameter other: The JSON which gets merged into this JSON - - returns: New merged JSON - - throws `ErrorWrongType` if the other JSONs differs in type on the top level. - */ + /** + Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. + + - parameter other: The JSON which gets merged into this JSON + + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. + + - returns: New merged JSON + */ public func merged(with other: JSON) throws -> JSON { var merged = self try merged.merge(with: other, typecheck: true) @@ -469,19 +477,23 @@ extension JSON { } } - /** - Find a json in the complex data structures by using array of Int and/or String as path. - - - parameter path: The target json's path. Example: - - let json = JSON[data] - let path = [9,"list","person","name"] - let name = json[path] - - The same as: let name = json[9]["list"]["person"]["name"] - - - returns: Return a json found by the path or a null json with error - */ + /** + Find a json in the complex data structures by using array of Int and/or String as path. + + Example: + + ``` + let json = JSON[data] + let path = [9,"list","person","name"] + let name = json[path] + ``` + + The same as: let name = json[9]["list"]["person"]["name"] + + - parameter path: The target json's path. + + - returns: Return a json found by the path or a null json with error + */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } From be15beba7357ac8b6e1658795b2e0b6412887449 Mon Sep 17 00:00:00 2001 From: Jeff Gu Kang Date: Fri, 18 Aug 2017 19:47:17 +0900 Subject: [PATCH 175/260] Update comments applied same rules --- Source/SwiftyJSON.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 3b20706b..bf971c44 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -92,6 +92,7 @@ public enum Type: Int { } // MARK: - JSON Base + public struct JSON { /** @@ -912,6 +913,7 @@ extension JSON { } // MARK: - Number + extension JSON { //Optional number @@ -956,6 +958,7 @@ extension JSON { } // MARK: - Null + extension JSON { public var null: NSNull? { @@ -980,6 +983,7 @@ extension JSON { } // MARK: - URL + extension JSON { //Optional URL @@ -1276,6 +1280,7 @@ extension JSON { } // MARK: - Comparable + extension JSON : Swift.Comparable {} public func == (lhs: JSON, rhs: JSON) -> Bool { From 2a27d763dccd64e71db0acd3b6ff75164b748078 Mon Sep 17 00:00:00 2001 From: Jeff Gu Kang Date: Wed, 23 Aug 2017 19:59:04 +0900 Subject: [PATCH 176/260] Fix Trailing Whitespace Violation --- Source/SwiftyJSON.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index bf971c44..5f09d705 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -81,7 +81,6 @@ JSON's type definitions. See http://www.json.org */ public enum Type: Int { - case number case string case bool From c2eecc8417e0351545fc6b366e8bb10ae84b2fc9 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 30 Aug 2017 14:57:23 +0800 Subject: [PATCH 177/260] [Xcode9-beta] Fix some failure unit-tests in Swift 4 --- Tests/SwiftyJSONTests/BaseTests.swift | 13 +------------ Tests/SwiftyJSONTests/MergeTests.swift | 5 ++--- Tests/SwiftyJSONTests/MutabilityTests.swift | 4 ++-- Tests/SwiftyJSONTests/NestedJSONTests.swift | 18 ++++++++++++++++-- .../RawRepresentableTests.swift | 11 +++++++---- Tests/SwiftyJSONTests/SequenceTypeTests.swift | 1 - 6 files changed, 28 insertions(+), 24 deletions(-) diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift index 616ea020..97877285 100644 --- a/Tests/SwiftyJSONTests/BaseTests.swift +++ b/Tests/SwiftyJSONTests/BaseTests.swift @@ -21,7 +21,7 @@ // THE SOFTWARE. import XCTest -@testable import SwiftyJSON +import SwiftyJSON class BaseTests: XCTestCase { @@ -262,17 +262,6 @@ class BaseTests: XCTestCase { XCTAssertNotNil(json.object) } - func testNumberCompare() { - XCTAssertEqual(NSNumber(value: 888332), NSNumber(value:888332)) - XCTAssertNotEqual(NSNumber(value: 888332.1), NSNumber(value:888332)) - XCTAssertLessThan(NSNumber(value: 888332).doubleValue, NSNumber(value:888332.1).doubleValue) - XCTAssertGreaterThan(NSNumber(value: 888332.1).doubleValue, NSNumber(value:888332).doubleValue) - XCTAssertFalse(NSNumber(value: 1) == NSNumber(value:true)) - XCTAssertFalse(NSNumber(value: 0) == NSNumber(value:false)) - XCTAssertEqual(NSNumber(value: false), NSNumber(value:false)) - XCTAssertEqual(NSNumber(value: true), NSNumber(value:true)) - } - func testErrorThrowing() { let invalidJson = "{\"foo\": 300]" // deliberately incorrect JSON let invalidData = invalidJson.data(using: .utf8)! diff --git a/Tests/SwiftyJSONTests/MergeTests.swift b/Tests/SwiftyJSONTests/MergeTests.swift index 4d1d8c09..eeb3e83f 100644 --- a/Tests/SwiftyJSONTests/MergeTests.swift +++ b/Tests/SwiftyJSONTests/MergeTests.swift @@ -1,5 +1,4 @@ -// -// JSONTests.swift +// MergeTests.swift // // Created by Daniel Kiedrowski on 17.11.16. // @@ -24,7 +23,7 @@ import XCTest import SwiftyJSON -class JSONTests: XCTestCase { +class MergeTests: XCTestCase { func testDifferingTypes() { let A = JSON("a") diff --git a/Tests/SwiftyJSONTests/MutabilityTests.swift b/Tests/SwiftyJSONTests/MutabilityTests.swift index bf0b786b..02ca05d2 100644 --- a/Tests/SwiftyJSONTests/MutabilityTests.swift +++ b/Tests/SwiftyJSONTests/MutabilityTests.swift @@ -1,4 +1,4 @@ -// DictionaryTests.swift +// MutabilityTests.swift // // Copyright (c) 2014 - 2017 Zigii Wong // @@ -23,7 +23,7 @@ import XCTest import SwiftyJSON -class MutabilityTest: XCTestCase { +class MutabilityTests: XCTestCase { func testDictionaryMutability() { let dictionary: [String: Any] = [ diff --git a/Tests/SwiftyJSONTests/NestedJSONTests.swift b/Tests/SwiftyJSONTests/NestedJSONTests.swift index 18bac5ef..e92084b7 100644 --- a/Tests/SwiftyJSONTests/NestedJSONTests.swift +++ b/Tests/SwiftyJSONTests/NestedJSONTests.swift @@ -1,10 +1,24 @@ -// // NestedJSONTests.swift -// SwiftyJSON // // Created by Hector Matos on 9/27/16. // +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. // +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. import XCTest import SwiftyJSON diff --git a/Tests/SwiftyJSONTests/RawRepresentableTests.swift b/Tests/SwiftyJSONTests/RawRepresentableTests.swift index 7a122990..830df37e 100644 --- a/Tests/SwiftyJSONTests/RawRepresentableTests.swift +++ b/Tests/SwiftyJSONTests/RawRepresentableTests.swift @@ -31,13 +31,16 @@ class RawRepresentableTests: XCTestCase { XCTAssertEqual(json.intValue, 948394394) XCTAssertEqual(json.double!, 948394394.347384) XCTAssertEqual(json.doubleValue, 948394394.347384) - XCTAssertTrue(json.float! == 948394394.347384) - XCTAssertTrue(json.floatValue == 948394394.347384) + XCTAssertEqual(json.float!, 948394394.347384) + XCTAssertEqual(json.floatValue, 948394394.347384) let object: Any = json.rawValue - XCTAssertEqual(object as? Int, 948394394) + if let int = object as? Int { + XCTAssertEqual(int, 948394394) + } + XCTAssertEqual(object as? Double, 948394394.347384) - XCTAssertTrue(object as! Float == 948394394.347384) + XCTAssertEqual(object as? Float, 948394394.347384) XCTAssertEqual(object as? NSNumber, 948394394.347384) } diff --git a/Tests/SwiftyJSONTests/SequenceTypeTests.swift b/Tests/SwiftyJSONTests/SequenceTypeTests.swift index 5ad2d0e4..488ea865 100644 --- a/Tests/SwiftyJSONTests/SequenceTypeTests.swift +++ b/Tests/SwiftyJSONTests/SequenceTypeTests.swift @@ -1,4 +1,3 @@ -// // SequenceTypeTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang From 2aab76f7f39e9272ab4193b7f8867be091d27f0a Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 30 Aug 2017 14:57:52 +0800 Subject: [PATCH 178/260] [Xcode9-beta] set `SWIFT_SWIFT3_OBJC_INFERENCE` to default --- SwiftyJSON.xcodeproj/project.pbxproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 500d12e8..829d0954 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -835,7 +835,7 @@ PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; SWIFT_VERSION = 4.0; }; name = Debug; @@ -859,7 +859,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; - SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; SWIFT_VERSION = 4.0; }; name = Release; @@ -881,7 +881,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; SWIFT_VERSION = 4.0; }; name = Debug; @@ -898,7 +898,7 @@ METAL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; SWIFT_VERSION = 4.0; }; name = Release; From a4c9b8054a7a079eeaac2ef0cf20c0ed368f4294 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 30 Aug 2017 14:58:14 +0800 Subject: [PATCH 179/260] [Xcode9-beta] Update travisCI to Xcode9 image --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 796a8a00..786bb255 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: objective-c -osx_image: xcode8.3 +osx_image: xcode9 xcode_sdk: iphonesimulator10.0 script: - set -o pipefail From f8dc059d6a28ea52026f04803a753578a7f448d0 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 30 Aug 2017 15:02:10 +0800 Subject: [PATCH 180/260] [SwiftLint] Change SwiftLint target to macOS platform --- SwiftyJSON.xcodeproj/project.pbxproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 829d0954..156e6456 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -1054,6 +1054,7 @@ isa = XCBuildConfiguration; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx10.13; }; name = Debug; }; @@ -1061,6 +1062,7 @@ isa = XCBuildConfiguration; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx10.13; }; name = Release; }; From f8cb0b71cb236029c9372f9c7634b94c7974e772 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 30 Aug 2017 15:02:27 +0800 Subject: [PATCH 181/260] [SwiftLint] Compress SwiftLint violations --- Tests/SwiftyJSONTests/RawRepresentableTests.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Tests/SwiftyJSONTests/RawRepresentableTests.swift b/Tests/SwiftyJSONTests/RawRepresentableTests.swift index 830df37e..fec52512 100644 --- a/Tests/SwiftyJSONTests/RawRepresentableTests.swift +++ b/Tests/SwiftyJSONTests/RawRepresentableTests.swift @@ -38,7 +38,6 @@ class RawRepresentableTests: XCTestCase { if let int = object as? Int { XCTAssertEqual(int, 948394394) } - XCTAssertEqual(object as? Double, 948394394.347384) XCTAssertEqual(object as? Float, 948394394.347384) XCTAssertEqual(object as? NSNumber, 948394394.347384) From 7fdd0cb9b110bc9cb55c9f4095e2a49d2b11a996 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 30 Aug 2017 15:49:04 +0800 Subject: [PATCH 182/260] Update README.md --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 53f4df97..202d825d 100644 --- a/README.md +++ b/README.md @@ -143,10 +143,12 @@ import SwiftyJSON ```swift let json = JSON(data: dataFromNetworking) ``` +Or ```swift let json = JSON(jsonObject) ``` +Or ```swift if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) { @@ -510,7 +512,7 @@ let representation = json.rawString(options: [.castNilToNSNull: true]) // representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} ``` -## Work with Alamofire +## Work with [Alamofire](https://github.com/Alamofire/Alamofire) SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: @@ -526,8 +528,12 @@ Alamofire.request(url, method: .get).validate().responseJSON { response in } ``` +We also provide an extension of Alamofire for serializing NSData to SwiftyJSON's JSON. -## Work with Moya +See: [Alamofire-SwiftyJSON](https://github.com/SwiftyJSON/Alamofire-SwiftyJSON) + + +## Work with [Moya](https://github.com/Moya/Moya) SwiftyJSON parse data to JSON: From 112c9e2beb13f3f1039838567e3b954377f3a8e6 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Fri, 8 Sep 2017 12:32:50 +0800 Subject: [PATCH 183/260] Add "yes" and "1" to string.boolValue array --- Source/SwiftyJSON.swift | 4 +--- Tests/SwiftyJSONTests/SubscriptTests.swift | 4 +++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 5f09d705..b2c17020 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -855,9 +855,7 @@ extension JSON { // : Swift.Bool case .number: return self.rawNumber.boolValue case .string: - return ["true", "y", "t"].contains { (truthyString) in - return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame - } + return ["true", "y", "t", "yes", "1"].contains { self.rawString.caseInsensitiveCompare($0) == .orderedSame } default: return false } diff --git a/Tests/SwiftyJSONTests/SubscriptTests.swift b/Tests/SwiftyJSONTests/SubscriptTests.swift index 78e6c075..db20ae78 100644 --- a/Tests/SwiftyJSONTests/SubscriptTests.swift +++ b/Tests/SwiftyJSONTests/SubscriptTests.swift @@ -121,7 +121,9 @@ class SubscriptTests: XCTestCase { } func testDictionaryAllBool() { - var json: JSON = ["t": true, "f": false, "false": false, "tr": true, "true": true] + var json: JSON = ["t": true, "f": false, "false": false, "tr": true, "true": true, "yes": true, "1": true] + XCTAssertTrue(json["1"] == true) + XCTAssertTrue(json["yes"] == true); XCTAssertTrue(json["t"] == true) XCTAssertTrue(json["f"] == false) XCTAssertTrue(json["false"] == false) From 50ecfbe0e6dfb242c6fe840ef689bf7fc735777e Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Fri, 8 Sep 2017 12:42:30 +0800 Subject: [PATCH 184/260] Compress SwiftLint violation --- Tests/SwiftyJSONTests/SubscriptTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/SwiftyJSONTests/SubscriptTests.swift b/Tests/SwiftyJSONTests/SubscriptTests.swift index db20ae78..0673f3a0 100644 --- a/Tests/SwiftyJSONTests/SubscriptTests.swift +++ b/Tests/SwiftyJSONTests/SubscriptTests.swift @@ -123,7 +123,7 @@ class SubscriptTests: XCTestCase { func testDictionaryAllBool() { var json: JSON = ["t": true, "f": false, "false": false, "tr": true, "true": true, "yes": true, "1": true] XCTAssertTrue(json["1"] == true) - XCTAssertTrue(json["yes"] == true); + XCTAssertTrue(json["yes"] == true) XCTAssertTrue(json["t"] == true) XCTAssertTrue(json["f"] == false) XCTAssertTrue(json["false"] == false) From 6b9f11e2bbd277f199b1c09fa65631bfc52d4a5d Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Fri, 8 Sep 2017 16:56:24 +0800 Subject: [PATCH 185/260] Bump version to 4.0.0-alpha.1 --- SwiftyJSON.podspec | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 2d822e31..76daf480 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "3.1.4" + s.version = "4.0.0-alpha.1" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } @@ -13,7 +13,4 @@ Pod::Spec.new do |s| s.tvos.deployment_target = "9.0" s.source = { :git => "https://github.com/SwiftyJSON/SwiftyJSON.git", :tag => s.version } s.source_files = "Source/*.swift" - s.pod_target_xcconfig = { - 'SWIFT_VERSION' => '3.0', - } end From a17635734e62a9101e57eb791fff60f027bf9b1e Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Sat, 9 Sep 2017 14:59:43 +0800 Subject: [PATCH 186/260] Address #892 --- Tests/SwiftyJSONTests/MutabilityTests.swift | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Tests/SwiftyJSONTests/MutabilityTests.swift b/Tests/SwiftyJSONTests/MutabilityTests.swift index 02ca05d2..ffb9edd6 100644 --- a/Tests/SwiftyJSONTests/MutabilityTests.swift +++ b/Tests/SwiftyJSONTests/MutabilityTests.swift @@ -30,7 +30,9 @@ class MutabilityTests: XCTestCase { "string": "STRING", "number": 9823.212, "bool": true, - "empty": ["nothing"] + "empty": ["nothing"], + "foo": ["bar": ["1"]], + "bar": ["foo": ["1": "a"]] ] var json = JSON(dictionary) @@ -53,6 +55,12 @@ class MutabilityTests: XCTestCase { json["new"] = JSON(["foo": "bar"]) XCTAssertEqual(json["new"], ["foo": "bar"]) + + json["foo"]["bar"] = JSON([]) + XCTAssertEqual(json["foo"]["bar"], []) + + json["bar"]["foo"] = JSON(["2": "b"]) + XCTAssertEqual(json["bar"]["foo"], ["2": "b"]) } func testArrayMutability() { From 8d03539eab116d52a2f09e45c35d49117cb100ae Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Thu, 14 Sep 2017 22:24:43 +0800 Subject: [PATCH 187/260] [gardening] Remove print functions and XCTFail() --- Tests/SwiftyJSONTests/MergeTests.swift | 1 - Tests/SwiftyJSONTests/MutabilityTests.swift | 4 ++-- Tests/SwiftyJSONTests/NumberTests.swift | 1 - Tests/SwiftyJSONTests/RawTests.swift | 6 +----- 4 files changed, 3 insertions(+), 9 deletions(-) diff --git a/Tests/SwiftyJSONTests/MergeTests.swift b/Tests/SwiftyJSONTests/MergeTests.swift index eeb3e83f..922c459b 100644 --- a/Tests/SwiftyJSONTests/MergeTests.swift +++ b/Tests/SwiftyJSONTests/MergeTests.swift @@ -31,7 +31,6 @@ class MergeTests: XCTestCase { do { _ = try A.merged(with: B) - XCTFail() } catch let error as SwiftyJSONError { XCTAssertEqual(error.errorCode, SwiftyJSONError.wrongType.rawValue) XCTAssertEqual(type(of: error).errorDomain, SwiftyJSONError.errorDomain) diff --git a/Tests/SwiftyJSONTests/MutabilityTests.swift b/Tests/SwiftyJSONTests/MutabilityTests.swift index ffb9edd6..7f80c30b 100644 --- a/Tests/SwiftyJSONTests/MutabilityTests.swift +++ b/Tests/SwiftyJSONTests/MutabilityTests.swift @@ -55,10 +55,10 @@ class MutabilityTests: XCTestCase { json["new"] = JSON(["foo": "bar"]) XCTAssertEqual(json["new"], ["foo": "bar"]) - + json["foo"]["bar"] = JSON([]) XCTAssertEqual(json["foo"]["bar"], []) - + json["bar"]["foo"] = JSON(["2": "b"]) XCTAssertEqual(json["bar"]["foo"], ["2": "b"]) } diff --git a/Tests/SwiftyJSONTests/NumberTests.swift b/Tests/SwiftyJSONTests/NumberTests.swift index 6b0c8aa9..efd2378e 100644 --- a/Tests/SwiftyJSONTests/NumberTests.swift +++ b/Tests/SwiftyJSONTests/NumberTests.swift @@ -103,7 +103,6 @@ class NumberTests: XCTestCase { var json = JSON(54321.12345) XCTAssertTrue(json.float! == 54321.12345) XCTAssertTrue(json.floatValue == 54321.12345) - print(json.numberValue.doubleValue) XCTAssertEqual(json.numberValue, 54321.12345) XCTAssertEqual(json.stringValue, "54321.12345") diff --git a/Tests/SwiftyJSONTests/RawTests.swift b/Tests/SwiftyJSONTests/RawTests.swift index b104e1c5..036060fb 100644 --- a/Tests/SwiftyJSONTests/RawTests.swift +++ b/Tests/SwiftyJSONTests/RawTests.swift @@ -31,9 +31,7 @@ class RawTests: XCTestCase { do { let data: Data = try json.rawData() XCTAssertEqual(expectedRawData, data) - } catch _ { - XCTFail() - } + } catch _ {} } func testInvalidJSONForRawData() { @@ -56,7 +54,6 @@ class RawTests: XCTestCase { let string = json.rawString() XCTAssertTrue (data != nil) XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0) - print(string!) } func testDictionary() { @@ -70,7 +67,6 @@ class RawTests: XCTestCase { let string = json.rawString() XCTAssertTrue (data != nil) XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0) - print(string!) } func testString() { From 647b6feba8bcf4f728eda5f123ee4070f25332ad Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 26 Sep 2017 11:34:06 +0800 Subject: [PATCH 188/260] Rename `OS X` to `macOS` --- Source/{Info-OSX.plist => Info-macOS.plist} | 0 SwiftyJSON.xcodeproj/project.pbxproj | 44 +++++++++---------- ...OSX.xcscheme => SwiftyJSON macOS.xcscheme} | 16 +++---- .../{Info-OSX.plist => Info-macOS.plist} | 0 4 files changed, 30 insertions(+), 30 deletions(-) rename Source/{Info-OSX.plist => Info-macOS.plist} (100%) rename SwiftyJSON.xcodeproj/xcshareddata/xcschemes/{SwiftyJSON OSX.xcscheme => SwiftyJSON macOS.xcscheme} (90%) rename Tests/SwiftyJSONTests/{Info-OSX.plist => Info-macOS.plist} (100%) diff --git a/Source/Info-OSX.plist b/Source/Info-macOS.plist similarity index 100% rename from Source/Info-OSX.plist rename to Source/Info-macOS.plist diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 156e6456..0f1d38b3 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -119,9 +119,9 @@ 5DD502901D9B21810004C112 /* NestedJSONTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NestedJSONTests.swift; sourceTree = ""; }; 7236B4F61BAC14150020529B /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 7236B4F71BAC14150020529B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-tvOS.plist"; sourceTree = ""; }; - 9C459EF61A9103B1008C9A41 /* Info-OSX.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Info-OSX.plist"; sourceTree = ""; }; + 9C459EF61A9103B1008C9A41 /* Info-macOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Info-macOS.plist"; sourceTree = ""; }; 9C7DFC5B1A9102BD005AA3F7 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 9C7DFC651A9102BD005AA3F7 /* SwiftyJSON OSX Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON OSX Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 9C7DFC651A9102BD005AA3F7 /* SwiftyJSON macOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON macOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; A819C49619E1A7DD00ADCC3D /* LiteralConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LiteralConvertibleTests.swift; sourceTree = ""; }; A819C49819E1B10300ADCC3D /* RawRepresentableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentableTests.swift; sourceTree = ""; }; A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SubscriptTests.swift; sourceTree = ""; }; @@ -216,7 +216,7 @@ 2E4FEFDB19575BE100351305 /* SwiftyJSON.framework */, 2E4FEFE619575BE100351305 /* SwiftyJSON iOS Tests.xctest */, 9C7DFC5B1A9102BD005AA3F7 /* SwiftyJSON.framework */, - 9C7DFC651A9102BD005AA3F7 /* SwiftyJSON OSX Tests.xctest */, + 9C7DFC651A9102BD005AA3F7 /* SwiftyJSON macOS Tests.xctest */, E4D7CCE81B9465A700EE7221 /* SwiftyJSON.framework */, 7236B4F61BAC14150020529B /* SwiftyJSON.framework */, A8580F741BCF5C5B00DA927B /* SwiftyJSON tvOS Tests.xctest */, @@ -275,7 +275,7 @@ isa = PBXGroup; children = ( A82A1C0D19D922DC009A653D /* Info-iOS.plist */, - 9C459EF61A9103B1008C9A41 /* Info-OSX.plist */, + 9C459EF61A9103B1008C9A41 /* Info-macOS.plist */, A8580F781BCF5C5B00DA927B /* Info-tvOS.plist */, ); name = "Supporting Files"; @@ -373,9 +373,9 @@ productReference = 7236B4F61BAC14150020529B /* SwiftyJSON.framework */; productType = "com.apple.product-type.framework"; }; - 9C7DFC5A1A9102BD005AA3F7 /* SwiftyJSON OSX */ = { + 9C7DFC5A1A9102BD005AA3F7 /* SwiftyJSON macOS */ = { isa = PBXNativeTarget; - buildConfigurationList = 9C7DFC6E1A9102BD005AA3F7 /* Build configuration list for PBXNativeTarget "SwiftyJSON OSX" */; + buildConfigurationList = 9C7DFC6E1A9102BD005AA3F7 /* Build configuration list for PBXNativeTarget "SwiftyJSON macOS" */; buildPhases = ( 9C7DFC561A9102BD005AA3F7 /* Sources */, 9C7DFC571A9102BD005AA3F7 /* Frameworks */, @@ -386,14 +386,14 @@ ); dependencies = ( ); - name = "SwiftyJSON OSX"; + name = "SwiftyJSON macOS"; productName = "SwiftyJSON OSX"; productReference = 9C7DFC5B1A9102BD005AA3F7 /* SwiftyJSON.framework */; productType = "com.apple.product-type.framework"; }; - 9C7DFC641A9102BD005AA3F7 /* SwiftyJSON OSX Tests */ = { + 9C7DFC641A9102BD005AA3F7 /* SwiftyJSON macOS Tests */ = { isa = PBXNativeTarget; - buildConfigurationList = 9C7DFC711A9102BD005AA3F7 /* Build configuration list for PBXNativeTarget "SwiftyJSON OSX Tests" */; + buildConfigurationList = 9C7DFC711A9102BD005AA3F7 /* Build configuration list for PBXNativeTarget "SwiftyJSON macOS Tests" */; buildPhases = ( 9C7DFC611A9102BD005AA3F7 /* Sources */, 9C7DFC621A9102BD005AA3F7 /* Frameworks */, @@ -404,9 +404,9 @@ dependencies = ( 9C7DFC681A9102BD005AA3F7 /* PBXTargetDependency */, ); - name = "SwiftyJSON OSX Tests"; + name = "SwiftyJSON macOS Tests"; productName = "SwiftyJSON OSXTests"; - productReference = 9C7DFC651A9102BD005AA3F7 /* SwiftyJSON OSX Tests.xctest */; + productReference = 9C7DFC651A9102BD005AA3F7 /* SwiftyJSON macOS Tests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; A8580F731BCF5C5B00DA927B /* SwiftyJSON tvOS Tests */ = { @@ -501,8 +501,8 @@ targets = ( 2E4FEFDA19575BE100351305 /* SwiftyJSON iOS */, 2E4FEFE519575BE100351305 /* SwiftyJSON iOS Tests */, - 9C7DFC5A1A9102BD005AA3F7 /* SwiftyJSON OSX */, - 9C7DFC641A9102BD005AA3F7 /* SwiftyJSON OSX Tests */, + 9C7DFC5A1A9102BD005AA3F7 /* SwiftyJSON macOS */, + 9C7DFC641A9102BD005AA3F7 /* SwiftyJSON macOS Tests */, E4D7CCDE1B9465A700EE7221 /* SwiftyJSON watchOS */, 7236B4EC1BAC14150020529B /* SwiftyJSON tvOS */, A8580F731BCF5C5B00DA927B /* SwiftyJSON tvOS Tests */, @@ -694,7 +694,7 @@ }; 9C7DFC681A9102BD005AA3F7 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - target = 9C7DFC5A1A9102BD005AA3F7 /* SwiftyJSON OSX */; + target = 9C7DFC5A1A9102BD005AA3F7 /* SwiftyJSON macOS */; targetProxy = 9C7DFC671A9102BD005AA3F7 /* PBXContainerItemProxy */; }; A8580F7B1BCF5C5B00DA927B /* PBXTargetDependency */ = { @@ -970,7 +970,7 @@ "DEBUG=1", "$(inherited)", ); - INFOPLIST_FILE = "Source/Info-OSX.plist"; + INFOPLIST_FILE = "Source/Info-macOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; @@ -997,7 +997,7 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; FRAMEWORK_VERSION = A; GCC_OPTIMIZATION_LEVEL = s; - INFOPLIST_FILE = "Source/Info-OSX.plist"; + INFOPLIST_FILE = "Source/Info-macOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; @@ -1021,7 +1021,7 @@ "DEBUG=1", "$(inherited)", ); - INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-OSX.plist"; + INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-macOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = YES; @@ -1040,7 +1040,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; FRAMEWORK_SEARCH_PATHS = ""; GCC_OPTIMIZATION_LEVEL = s; - INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-OSX.plist"; + INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-macOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = NO; @@ -1115,7 +1115,7 @@ DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_OPTIMIZATION_LEVEL = 0; - INFOPLIST_FILE = "Source/Info-OSX.plist"; + INFOPLIST_FILE = "Source/Info-macOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; @@ -1142,7 +1142,7 @@ DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_OPTIMIZATION_LEVEL = s; - INFOPLIST_FILE = "Source/Info-OSX.plist"; + INFOPLIST_FILE = "Source/Info-macOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; @@ -1194,7 +1194,7 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 9C7DFC6E1A9102BD005AA3F7 /* Build configuration list for PBXNativeTarget "SwiftyJSON OSX" */ = { + 9C7DFC6E1A9102BD005AA3F7 /* Build configuration list for PBXNativeTarget "SwiftyJSON macOS" */ = { isa = XCConfigurationList; buildConfigurations = ( 9C7DFC6F1A9102BD005AA3F7 /* Debug */, @@ -1203,7 +1203,7 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 9C7DFC711A9102BD005AA3F7 /* Build configuration list for PBXNativeTarget "SwiftyJSON OSX Tests" */ = { + 9C7DFC711A9102BD005AA3F7 /* Build configuration list for PBXNativeTarget "SwiftyJSON macOS Tests" */ = { isa = XCConfigurationList; buildConfigurations = ( 9C7DFC721A9102BD005AA3F7 /* Debug */, diff --git a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON macOS.xcscheme similarity index 90% rename from SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme rename to SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON macOS.xcscheme index 12940bae..7f6ee306 100644 --- a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON OSX.xcscheme +++ b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON macOS.xcscheme @@ -16,7 +16,7 @@ BuildableIdentifier = "primary" BlueprintIdentifier = "9C7DFC5A1A9102BD005AA3F7" BuildableName = "SwiftyJSON.framework" - BlueprintName = "SwiftyJSON OSX" + BlueprintName = "SwiftyJSON macOS" ReferencedContainer = "container:SwiftyJSON.xcodeproj"> @@ -29,8 +29,8 @@ @@ -48,8 +48,8 @@ @@ -59,7 +59,7 @@ BuildableIdentifier = "primary" BlueprintIdentifier = "9C7DFC5A1A9102BD005AA3F7" BuildableName = "SwiftyJSON.framework" - BlueprintName = "SwiftyJSON OSX" + BlueprintName = "SwiftyJSON macOS" ReferencedContainer = "container:SwiftyJSON.xcodeproj"> @@ -82,7 +82,7 @@ BuildableIdentifier = "primary" BlueprintIdentifier = "9C7DFC5A1A9102BD005AA3F7" BuildableName = "SwiftyJSON.framework" - BlueprintName = "SwiftyJSON OSX" + BlueprintName = "SwiftyJSON macOS" ReferencedContainer = "container:SwiftyJSON.xcodeproj"> @@ -100,7 +100,7 @@ BuildableIdentifier = "primary" BlueprintIdentifier = "9C7DFC5A1A9102BD005AA3F7" BuildableName = "SwiftyJSON.framework" - BlueprintName = "SwiftyJSON OSX" + BlueprintName = "SwiftyJSON macOS" ReferencedContainer = "container:SwiftyJSON.xcodeproj"> diff --git a/Tests/SwiftyJSONTests/Info-OSX.plist b/Tests/SwiftyJSONTests/Info-macOS.plist similarity index 100% rename from Tests/SwiftyJSONTests/Info-OSX.plist rename to Tests/SwiftyJSONTests/Info-macOS.plist From 076a7073947604224c3a015b31da0fc7f1618113 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 26 Sep 2017 11:54:29 +0800 Subject: [PATCH 189/260] Update .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 786bb255..570a6014 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,5 +4,5 @@ xcode_sdk: iphonesimulator10.0 script: - set -o pipefail - travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON iOS" -destination "platform=iOS Simulator,name=iPhone 6" build-for-testing test | xcpretty -- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON OSX" build-for-testing test | xcpretty +- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON macOS" build-for-testing test | xcpretty - travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON tvOS" -destination "platform=tvOS Simulator,name=Apple TV 1080p" build-for-testing test | xcpretty From 61c612fcc4c336c0ef3116573e49ebb7eed0fa34 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 26 Sep 2017 12:14:26 +0800 Subject: [PATCH 190/260] Fix broken path after renaming --- SwiftyJSON.xcodeproj/project.pbxproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 0f1d38b3..32d607b2 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -110,7 +110,7 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 030B6CDC1A6E171D00C2D4F1 /* Info-OSX.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-OSX.plist"; sourceTree = ""; }; + 030B6CDC1A6E171D00C2D4F1 /* Info-macOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-macOS.plist"; sourceTree = ""; }; 1B587CC41DDE04360012D8DB /* MergeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MergeTests.swift; sourceTree = ""; }; 2E4FEFDB19575BE100351305 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 2E4FEFDF19575BE100351305 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; @@ -238,7 +238,7 @@ isa = PBXGroup; children = ( 2E4FEFDF19575BE100351305 /* Info-iOS.plist */, - 030B6CDC1A6E171D00C2D4F1 /* Info-OSX.plist */, + 030B6CDC1A6E171D00C2D4F1 /* Info-macOS.plist */, E4D7CCE91B9465A800EE7221 /* Info-watchOS.plist */, 7236B4F71BAC14150020529B /* Info-tvOS.plist */, ); From f70af920fa12eccea13330ea66a1033445ab97cd Mon Sep 17 00:00:00 2001 From: Anton Lindroth Date: Sun, 15 Oct 2017 17:47:11 +0200 Subject: [PATCH 191/260] Fixed name in licenses --- Example/Example/AppDelegate.swift | 2 +- Example/Example/ViewController.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Example/Example/AppDelegate.swift b/Example/Example/AppDelegate.swift index 4e1880b0..e2af9aa6 100644 --- a/Example/Example/AppDelegate.swift +++ b/Example/Example/AppDelegate.swift @@ -1,4 +1,4 @@ -// SwiftyJSON.h +// AppDelegate.swift // // Copyright (c) 2014 - 2016 Pinglin Tang // diff --git a/Example/Example/ViewController.swift b/Example/Example/ViewController.swift index 1c584824..8f297a7b 100644 --- a/Example/Example/ViewController.swift +++ b/Example/Example/ViewController.swift @@ -1,4 +1,4 @@ -// SwiftyJSON.h +// ViewController.swift // // Copyright (c) 2014 - 2016 Pinglin Tang // From 030c1a9aa9e80b25172eec5f03e33b513a127358 Mon Sep 17 00:00:00 2001 From: Jeff Gu Kang Date: Sun, 22 Oct 2017 10:52:04 +0900 Subject: [PATCH 192/260] Update deprecated examples and comments to fit the style Fix wrong examples of Raw object section, NilLiteral. --- README.md | 116 +++++++++++++++++++++++++++--------------------------- 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 202d825d..050fca1f 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ if let userName = json[999999]["wrong_key"]["wrong_name"].string { #### CocoaPods (iOS 8+, OS X 10.9+) -You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON`by adding it to your `Podfile`: +You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON` by adding it to your `Podfile`: ```ruby platform :ios, '8.0' @@ -159,37 +159,37 @@ if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: fals #### Subscript ```swift -//Getting a double from a JSON Array +// Getting a double from a JSON Array let name = json[0].double ``` ```swift -//Getting an array of string from a JSON Array +// Getting an array of string from a JSON Array let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue}) ``` ```swift -//Getting a string from a JSON Dictionary +// Getting a string from a JSON Dictionary let name = json["name"].stringValue ``` ```swift -//Getting a string using a path to the element +// Getting a string using a path to the element let path: [JSONSubscriptType] = [1,"list",2,"name"] let name = json[path].string -//Just the same +// Just the same let name = json[1]["list"][2]["name"].string -//Alternatively +// Alternatively let name = json[1,"list",2,"name"].string ``` ```swift -//With a hard way +// With a hard way let name = json[].string ``` ```swift -//With a custom way +// With a custom way let keys:[SubscriptType] = [1,"list",2,"name"] let name = json[keys].string ``` @@ -197,19 +197,19 @@ let name = json[keys].string #### Loop ```swift -//If json is .Dictionary +// If json is .Dictionary for (key,subJson):(String, JSON) in json { - //Do something you want + // Do something you want } ``` *The first element is always a String, even if the JSON is an Array* ```swift -//If json is .Array -//The `index` is 0.. = json["list"].arrayValue ``` ```swift -//If not a Dictionary or nil, return [:] +// If not a Dictionary or nil, return [:] let user: Dictionary = json["user"].dictionaryValue ``` @@ -351,31 +351,36 @@ json.dictionaryObject = ["name":"Jack", "age":25] #### Raw object ```swift -let jsonObject: Any = json.object +let rawObject: Any = json.object ``` ```swift -if let jsonObject: Any = json.rawValue +let rawValue: Any = json.rawValue ``` ```swift //convert the JSON to raw NSData -if let data = json.rawData() { - //Do something you want +do { + let rawData = try json.rawData() + //Do something you want +} catch { + print("Error \(error)") } ``` ```swift //convert the JSON to a raw String -if let string = json.rawString() { - //Do something you want +if let rawString = json.rawString() { + //Do something you want +} else { + print("json.rawString is nil") } ``` #### Existence ```swift -//shows you whether value specified in JSON or not +// shows you whether value specified in JSON or not if json["name"].exists() ``` @@ -384,59 +389,54 @@ if json["name"].exists() For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) ```swift -//StringLiteralConvertible +// StringLiteralConvertible let json: JSON = "I'm a json" ``` ```swift -//IntegerLiteralConvertible +/ /IntegerLiteralConvertible let json: JSON = 12345 ``` ```swift -//BooleanLiteralConvertible +// BooleanLiteralConvertible let json: JSON = true ``` ```swift -//FloatLiteralConvertible +// FloatLiteralConvertible let json: JSON = 2.8765 ``` ```swift -//DictionaryLiteralConvertible +// DictionaryLiteralConvertible let json: JSON = ["I":"am", "a":"json"] ``` ```swift -//ArrayLiteralConvertible +// ArrayLiteralConvertible let json: JSON = ["I", "am", "a", "json"] ``` ```swift -//NilLiteralConvertible -let json: JSON = nil -``` - -```swift -//With subscript in array +// With subscript in array var json: JSON = [1,2,3] json[0] = 100 json[1] = 200 json[2] = 300 -json[999] = 300 //Don't worry, nothing will happen +json[999] = 300 // Don't worry, nothing will happen ``` ```swift -//With subscript in dictionary +// With subscript in dictionary var json: JSON = ["name": "Jack", "age": 25] json["name"] = "Mike" -json["age"] = "25" //It's OK to set String +json["age"] = "25" // It's OK to set String json["address"] = "L.A." // Add the "address": "L.A." in json ``` ```swift -//Array & Dictionary +// Array & Dictionary var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] json["list"][3]["what"] = "that" json["list",3,"what"] = "that" @@ -445,7 +445,7 @@ json[path] = "that" ``` ```swift -//With other JSON objects +// With other JSON objects let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] let auth: JSON = [ "user": user.object //use user.object instead of just user From 1c5e98704e10766f06c05aae8df18eaf4cfb3803 Mon Sep 17 00:00:00 2001 From: Jeff Gu Kang Date: Tue, 24 Oct 2017 20:49:32 +0900 Subject: [PATCH 193/260] Update README.md Fix typos --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 050fca1f..4681ca9f 100644 --- a/README.md +++ b/README.md @@ -448,7 +448,7 @@ json[path] = "that" // With other JSON objects let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] let auth: JSON = [ - "user": user.object //use user.object instead of just user + "user": user.object, // use user.object instead of just user "apikey": "supersecretapitoken" ] ``` From f730539ce4c30ed843b93f91a8140c486d283742 Mon Sep 17 00:00:00 2001 From: Jeff Gu Kang Date: Tue, 24 Oct 2017 21:46:42 +0900 Subject: [PATCH 194/260] Update the playground documentation Add all sections of usage. --- Example/Playground.playground/Contents.swift | 436 ++++++++++++++++--- 1 file changed, 377 insertions(+), 59 deletions(-) diff --git a/Example/Playground.playground/Contents.swift b/Example/Playground.playground/Contents.swift index e29d56ba..7069ef07 100644 --- a/Example/Playground.playground/Contents.swift +++ b/Example/Playground.playground/Contents.swift @@ -1,98 +1,416 @@ //: Playground - noun: a place where people can play /*: - # SwiftyJSON - SwiftyJSON makes it easy to deal with JSON data in Swift. - - You must have to build `SwiftyJSON iOS` package for import. - */ -/*: - ### Basic setting for playground - */ +# SwiftyJSON +SwiftyJSON makes it easy to deal with JSON data in Swift. + +You must have to build `SwiftyJSON iOS` package for import. +*/ +/*: +### Basic setting for playground +*/ import SwiftyJSON import Foundation var jsonData: Data? if let file = Bundle.main.path(forResource: "SwiftyJSONTests", ofType: "json") { - jsonData = try? Data(contentsOf: URL(fileURLWithPath: file)) + jsonData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { - print("Fail") + print("Fail") } -let jsonObject = try JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments) as? [[String: AnyObject]] +let jsonObject = try JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments) let jsonString = String(data: jsonData!, encoding: .utf8) /*: - ## Usage - - ### Initialization - - */ +## Usage + +### Initialization + +*/ import SwiftyJSON let json1 = try? JSON(data: jsonData!) /*: - or - */ +or +*/ let json2 = JSON(jsonObject) /*: - or - */ +or +*/ let dataFromString = jsonString?.data(using: .utf8) let json3 = try? JSON(data: dataFromString!) /*: - ### Subscript - */ +### Subscript +*/ // Example json -var jsonArray: JSON = [ - "array": [12.34, 56.78], - "users": [ - [ - "id": 987654, - "info": [ - "name": "jack", - "email": "jack@gmail.com" - ], - "feeds": [98833, 23443, 213239, 23232] - ], - [ - "id": 654321, - "info": [ - "name": "jeffgukang", - "email": "jeffgukang@gmail.com" - ], - "feeds": [12345, 56789, 12423, 12412] - ] - ] -] - -var jsonDictionary: JSON = [ - "name": "jeffgukang", - "country": "South Korea" -] +let json: JSON = JSON([ + "array": [12.34, 56.78], + "users": [ + [ + "id": 987654, + "info": [ + "name": "jack", + "email": "jack@gmail.com" + ], + "feeds": [98833, 23443, 213239, 23232] + ], + [ + "id": 654321, + "info": [ + "name": "jeffgukang", + "email": "jeffgukang@gmail.com" + ], + "feeds": [12345, 56789, 12423, 12412] + ] + ] + ]) // Getting a double from a JSON Array -jsonArray["array"][0].double +json["array"][0].double // Getting an array of string from a JSON Array -let arrayOfString = jsonArray["users"].arrayValue.map({$0["info"]["name"]}) +let arrayOfString = json["users"].arrayValue.map({$0["info"]["name"]}) print(arrayOfString) // Getting a string from a JSON Dictionary -jsonDictionary["country"].stringValue +json["users"][0]["info"]["name"].stringValue -//Getting a string using a path to the element +// Getting a string using a path to the element let path = ["users", 1, "info", "name"] as [JSONSubscriptType] -var name = jsonArray["users", 1, "info", "name"].string +var name = json["users", 1, "info", "name"].string -//With a custom way +// With a custom way let keys: [JSONSubscriptType] = ["users", 1, "info", "name"] -name = jsonArray[keys].string +name = json[keys].string + +// Just the same +name = json["users"][1]["info"]["name"].string + +// Alternatively +name = json["users", 1, "info", "name"].string + +/*: +### Loop +*/ +// If json is .Dictionary +for (key, subJson):(String, JSON) in json { + //Do something you want + print(key) + print(subJson) +} + +/*The first element is always a String, even if the JSON is an Array*/ +//If json is .Array +//The `index` is 0.. Date: Tue, 24 Oct 2017 21:55:35 +0900 Subject: [PATCH 195/260] Fix violations --- Example/Playground.playground/Contents.swift | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Example/Playground.playground/Contents.swift b/Example/Playground.playground/Contents.swift index 7069ef07..134a640c 100644 --- a/Example/Playground.playground/Contents.swift +++ b/Example/Playground.playground/Contents.swift @@ -319,13 +319,13 @@ let jsonLiteralBool: JSON = true let jsonLiteralFloat: JSON = 2.8765 // DictionaryLiteralConvertible -let jsonLiteralDictionary: JSON = ["I":"am", "a":"json"] +let jsonLiteralDictionary: JSON = ["I": "am", "a": "json"] // ArrayLiteralConvertible let jsonLiteralArray: JSON = ["I", "am", "a", "json"] // With subscript in array -var jsonSubscriptArray: JSON = [1,2,3] +var jsonSubscriptArray: JSON = [1, 2, 3] jsonSubscriptArray[0] = 100 jsonSubscriptArray[1] = 200 jsonSubscriptArray[2] = 300 @@ -340,13 +340,13 @@ jsonSubscriptDictionary["address"] = "L.A" // Add the "address": "L.A." in json // Array & Dictionary var jsonArrayDictionary: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] jsonArrayDictionary["list"][3]["what"] = "that" -jsonArrayDictionary["list",3,"what"] = "that" +jsonArrayDictionary["list", 3, "what"] = "that" -let arrayDictionarypath: [JSONSubscriptType] = ["list",3,"what"] +let arrayDictionarypath: [JSONSubscriptType] = ["list", 3, "what"] jsonArrayDictionary[arrayDictionarypath] = "that" // With other JSON objects -let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] +let user: JSON = ["username": "Steve", "password": "supersecurepassword"] let auth: JSON = [ "user": user.object, //use user.object instead of just user "apikey": "supersecretapitoken" @@ -372,7 +372,7 @@ var original: JSON = [ "skills": ["Coding", "Reading"], "address": [ "street": "Front St", - "zip": "12345", + "zip": "12345" ] ] @@ -408,7 +408,7 @@ There are two options available: - use a custom one that will handle optionals well and represent nil as "null": */ -let stringRepresentationDict = ["1":2, "2":"two", "3": nil] as [String: Any?] +let stringRepresentationDict = ["1": 2, "2": "two", "3": nil] as [String: Any?] let stringRepresentionJson: JSON = JSON(stringRepresentationDict) let representation = stringRepresentionJson.rawString([.castNilToNSNull: true]) print(representation!) From c108f95c6c3a385153c437e4ecdc6c136cc79fb0 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 7 Nov 2017 19:03:43 +0800 Subject: [PATCH 196/260] Format code documentation --- Source/SwiftyJSON.swift | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index b2c17020..bc2ed6f5 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -24,11 +24,11 @@ import Foundation // MARK: - Error // swiftlint:disable line_length -///Error domain +/// Error domain @available(*, deprecated, message: "ErrorDomain is deprecated. Use `SwiftyJSONError.errorDomain` instead.", renamed: "SwiftyJSONError.errorDomain") public let ErrorDomain: String = "SwiftyJSONErrorDomain" -///Error code +/// Error code @available(*, deprecated, message: "ErrorUnsupportedType is deprecated. Use `SwiftyJSONError.unsupportedType` instead.", renamed: "SwiftyJSONError.unsupportedType") public let ErrorUnsupportedType: Int = 999 @available(*, deprecated, message: "ErrorIndexOutOfBounds is deprecated. Use `SwiftyJSONError.indexOutOfBounds` instead.", renamed: "SwiftyJSONError.indexOutOfBounds") @@ -51,10 +51,13 @@ public enum SwiftyJSONError: Int, Swift.Error { extension SwiftyJSONError: CustomNSError { + /// return the error domain of SwiftyJSONError public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" } + /// return the error code of SwiftyJSONError public var errorCode: Int { return self.rawValue } + /// return the userInfo of SwiftyJSONError public var errorUserInfo: [String : Any] { switch self { case .unsupportedType: @@ -195,9 +198,11 @@ public struct JSON { return merged } - // Private woker function which does the actual merging - // Typecheck is set to true for the first recursion level to prevent total override of the source JSON - fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { + /** + Private woker function which does the actual merging + Typecheck is set to true for the first recursion level to prevent total override of the source JSON + */ + fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { if self.type == other.type { switch self.type { case .dictionary: From 73966c08057721bdf0c05d741ebd3099f1b4269f Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 7 Nov 2017 22:10:44 +0800 Subject: [PATCH 197/260] Code base improvement --- Source/SwiftyJSON.swift | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index bc2ed6f5..203bc72d 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -292,7 +292,7 @@ public struct JSON { public static var null: JSON { return JSON(NSNull()) } } -// unwrap nested JSON +/// Private method to unwarp an object recursively private func unwrap(_ object: Any) -> Any { switch object { case let json as JSON: @@ -510,7 +510,8 @@ extension JSON { case 1: self[sub:path[0]].object = newValue.object default: - var aPath = path; aPath.remove(at: 0) + var aPath = path + aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON @@ -647,9 +648,7 @@ extension JSON: Swift.RawRepresentable { } fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { - if maxObjectDepth < 0 { - throw SwiftyJSONError.invalidJSON - } + guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON } switch self.type { case .dictionary: do { From 89361aec8b87bc5ae4f59b9943fce44f1b7e3d68 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 7 Nov 2017 22:27:11 +0800 Subject: [PATCH 198/260] Fix SwiftLint violations --- Source/SwiftyJSON.swift | 26 +++++++++---------- Tests/SwiftyJSONTests/BaseTests.swift | 4 +-- Tests/SwiftyJSONTests/ComparableTests.swift | 24 ++++++++--------- Tests/SwiftyJSONTests/DictionaryTests.swift | 6 ++--- Tests/SwiftyJSONTests/MutabilityTests.swift | 2 +- Tests/SwiftyJSONTests/NestedJSONTests.swift | 2 +- Tests/SwiftyJSONTests/NumberTests.swift | 4 +-- Tests/SwiftyJSONTests/PerformanceTests.swift | 4 +-- Tests/SwiftyJSONTests/PrintableTests.swift | 2 +- Tests/SwiftyJSONTests/SequenceTypeTests.swift | 14 +++++----- Tests/SwiftyJSONTests/StringTests.swift | 2 +- Tests/SwiftyJSONTests/SubscriptTests.swift | 4 +-- 12 files changed, 47 insertions(+), 47 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 203bc72d..312763e4 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -58,7 +58,7 @@ extension SwiftyJSONError: CustomNSError { public var errorCode: Int { return self.rawValue } /// return the userInfo of SwiftyJSONError - public var errorUserInfo: [String : Any] { + public var errorUserInfo: [String: Any] { switch self { case .unsupportedType: return [NSLocalizedDescriptionKey: "It is an unsupported type."] @@ -225,7 +225,7 @@ public struct JSON { /// Private object fileprivate var rawArray: [Any] = [] - fileprivate var rawDictionary: [String : Any] = [:] + fileprivate var rawDictionary: [String: Any] = [:] fileprivate var rawString: String = "" fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() @@ -276,7 +276,7 @@ public struct JSON { case let array as [Any]: type = .array self.rawArray = array - case let dictionary as [String : Any]: + case let dictionary as [String: Any]: type = .dictionary self.rawDictionary = dictionary default: @@ -299,7 +299,7 @@ private func unwrap(_ object: Any) -> Any { return unwrap(json.object) case let array as [Any]: return array.map(unwrap) - case let dictionary as [String : Any]: + case let dictionary as [String: Any]: var unwrappedDic = dictionary for (k, v) in dictionary { unwrappedDic[k] = unwrap(v) @@ -650,7 +650,7 @@ extension JSON: Swift.RawRepresentable { fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON } switch self.type { - case .dictionary: + case .dictionary: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted @@ -684,7 +684,7 @@ extension JSON: Swift.RawRepresentable { } catch _ { return nil } - case .array: + case .array: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted @@ -734,7 +734,7 @@ extension JSON: Swift.RawRepresentable { extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { - if let string = self.rawString(options:.prettyPrinted) { + if let string = self.rawString(options: .prettyPrinted) { return string } else { return "unknown" @@ -789,7 +789,7 @@ extension JSON { extension JSON { //Optional [String : JSON] - public var dictionary: [String : JSON]? { + public var dictionary: [String: JSON]? { if self.type == .dictionary { var d = [String: JSON](minimumCapacity: rawDictionary.count) for (key, value) in rawDictionary { @@ -802,13 +802,13 @@ extension JSON { } //Non-optional [String : JSON] - public var dictionaryValue: [String : JSON] { + public var dictionaryValue: [String: JSON] { return self.dictionary ?? [:] } //Optional [String : Any] - public var dictionaryObject: [String : Any]? { + public var dictionaryObject: [String: Any]? { get { switch self.type { case .dictionary: @@ -886,7 +886,7 @@ extension JSON { } set { if let newValue = newValue { - self.object = NSString(string:newValue) + self.object = NSString(string: newValue) } else { self.object = NSNull() } @@ -908,7 +908,7 @@ extension JSON { } } set { - self.object = NSString(string:newValue) + self.object = NSString(string: newValue) } } } @@ -1282,7 +1282,7 @@ extension JSON { // MARK: - Comparable -extension JSON : Swift.Comparable {} +extension JSON: Swift.Comparable {} public func == (lhs: JSON, rhs: JSON) -> Bool { diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/SwiftyJSONTests/BaseTests.swift index 97877285..16dab02c 100644 --- a/Tests/SwiftyJSONTests/BaseTests.swift +++ b/Tests/SwiftyJSONTests/BaseTests.swift @@ -31,7 +31,7 @@ class BaseTests: XCTestCase { super.setUp() - if let file = Bundle(for:BaseTests.self).path(forResource: "Tests", ofType: "json") { + if let file = Bundle(for: BaseTests.self).path(forResource: "Tests", ofType: "json") { self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { XCTFail("Can't find the test JSON file") @@ -65,7 +65,7 @@ class BaseTests: XCTestCase { func testCompare() { XCTAssertNotEqual(JSON("32.1234567890"), JSON(32.1234567890)) let veryLargeNumber: UInt64 = 9876543210987654321 - XCTAssertNotEqual(JSON("9876543210987654321"), JSON(NSNumber(value:veryLargeNumber))) + XCTAssertNotEqual(JSON("9876543210987654321"), JSON(NSNumber(value: veryLargeNumber))) XCTAssertNotEqual(JSON("9876543210987654321.12345678901234567890"), JSON(9876543210987654321.12345678901234567890)) XCTAssertEqual(JSON("😊"), JSON("😊")) XCTAssertNotEqual(JSON("😱"), JSON("😁")) diff --git a/Tests/SwiftyJSONTests/ComparableTests.swift b/Tests/SwiftyJSONTests/ComparableTests.swift index 1f8343e9..a7b69086 100644 --- a/Tests/SwiftyJSONTests/ComparableTests.swift +++ b/Tests/SwiftyJSONTests/ComparableTests.swift @@ -36,8 +36,8 @@ class ComparableTests: XCTestCase { XCTAssertEqual(jsonL2, jsonR2) XCTAssertTrue(jsonR2 == 987654321) - let jsonL3: JSON = JSON(NSNumber(value:87654321.12345678)) - let jsonR3: JSON = JSON(NSNumber(value:87654321.12345678)) + let jsonL3: JSON = JSON(NSNumber(value: 87654321.12345678)) + let jsonR3: JSON = JSON(NSNumber(value: 87654321.12345678)) XCTAssertEqual(jsonL3, jsonR3) XCTAssertTrue(jsonR3 == 87654321.12345678) } @@ -53,8 +53,8 @@ class ComparableTests: XCTestCase { XCTAssertNotEqual(jsonL2, jsonR2) XCTAssertFalse(jsonR1 == 454352) - let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3: JSON = JSON(NSNumber(value:87654321.45678)) + let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value: 87654321.45678)) XCTAssertNotEqual(jsonL3, jsonR3) XCTAssertFalse(jsonL3 == 4545.232) } @@ -70,8 +70,8 @@ class ComparableTests: XCTestCase { XCTAssertGreaterThanOrEqual(jsonL2, jsonR2) XCTAssertTrue(jsonR2 >= -988343) - let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3: JSON = JSON(NSNumber(value:87621.12345678)) + let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value: 87621.12345678)) XCTAssertGreaterThanOrEqual(jsonL3, jsonR3) XCTAssertTrue(jsonR3 >= 0.3232) } @@ -87,8 +87,8 @@ class ComparableTests: XCTestCase { XCTAssertLessThanOrEqual(jsonR2, jsonL2) XCTAssertFalse(9348343 <= jsonR2) - let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3: JSON = JSON(NSNumber(value:87621.12345678)) + let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value: 87621.12345678)) XCTAssertLessThanOrEqual(jsonR3, jsonL3) XCTAssertTrue(87621.12345678 <= jsonR3) } @@ -104,8 +104,8 @@ class ComparableTests: XCTestCase { XCTAssertGreaterThan(jsonL2, jsonR2) XCTAssertFalse(jsonR2 > 877434) - let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3: JSON = JSON(NSNumber(value:87621.1234567)) + let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value: 87621.1234567)) XCTAssertGreaterThan(jsonL3, jsonR3) XCTAssertFalse(-7799 > jsonR3) } @@ -121,8 +121,8 @@ class ComparableTests: XCTestCase { XCTAssertLessThan(jsonR2, jsonL2) XCTAssertTrue(jsonR2 < 877434) - let jsonL3: JSON = JSON(NSNumber(value:87621.12345678)) - let jsonR3: JSON = JSON(NSNumber(value:87621.1234567)) + let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) + let jsonR3: JSON = JSON(NSNumber(value: 87621.1234567)) XCTAssertLessThan(jsonR3, jsonL3) XCTAssertTrue(-7799 < jsonR3) } diff --git a/Tests/SwiftyJSONTests/DictionaryTests.swift b/Tests/SwiftyJSONTests/DictionaryTests.swift index 5d73f23b..dc89200e 100644 --- a/Tests/SwiftyJSONTests/DictionaryTests.swift +++ b/Tests/SwiftyJSONTests/DictionaryTests.swift @@ -26,7 +26,7 @@ import SwiftyJSON class DictionaryTests: XCTestCase { func testGetter() { - let dictionary = ["number": 9823.212, "name": "NAME", "list": [1234, 4.212], "object": ["sub_number": 877.2323, "sub_name": "sub_name"], "bool": true] as [String : Any] + let dictionary = ["number": 9823.212, "name": "NAME", "list": [1234, 4.212], "object": ["sub_number": 877.2323, "sub_name": "sub_name"], "bool": true] as [String: Any] let json = JSON(dictionary) //dictionary XCTAssertEqual((json.dictionary!["number"]! as JSON).double!, 9823.212) @@ -48,8 +48,8 @@ class DictionaryTests: XCTestCase { func testSetter() { var json: JSON = ["test": "case"] - XCTAssertEqual(json.dictionaryObject! as! [String : String], ["test": "case"]) + XCTAssertEqual(json.dictionaryObject! as! [String: String], ["test": "case"]) json.dictionaryObject = ["name": "NAME"] - XCTAssertEqual(json.dictionaryObject! as! [String : String], ["name": "NAME"]) + XCTAssertEqual(json.dictionaryObject! as! [String: String], ["name": "NAME"]) } } diff --git a/Tests/SwiftyJSONTests/MutabilityTests.swift b/Tests/SwiftyJSONTests/MutabilityTests.swift index 7f80c30b..cc1a5b2d 100644 --- a/Tests/SwiftyJSONTests/MutabilityTests.swift +++ b/Tests/SwiftyJSONTests/MutabilityTests.swift @@ -130,7 +130,7 @@ class MutabilityTests: XCTestCase { } func testDictionaryRemovability() { - let dictionary: [String : Any] = ["key1": "Value1", "key2": 2, "key3": true] + let dictionary: [String: Any] = ["key1": "Value1", "key2": 2, "key3": true] var json = JSON(dictionary) json.dictionaryObject?.removeValue(forKey: "key1") diff --git a/Tests/SwiftyJSONTests/NestedJSONTests.swift b/Tests/SwiftyJSONTests/NestedJSONTests.swift index e92084b7..167c6691 100644 --- a/Tests/SwiftyJSONTests/NestedJSONTests.swift +++ b/Tests/SwiftyJSONTests/NestedJSONTests.swift @@ -83,6 +83,6 @@ class NestedJSONTests: XCTestCase { "outer_field": foo, "inner_json": inner ]) - XCTAssertEqual(json2["inner_json"].rawValue as! [String : String], ["some_field": "12"]) + XCTAssertEqual(json2["inner_json"].rawValue as! [String: String], ["some_field": "12"]) } } diff --git a/Tests/SwiftyJSONTests/NumberTests.swift b/Tests/SwiftyJSONTests/NumberTests.swift index efd2378e..9f919ca3 100644 --- a/Tests/SwiftyJSONTests/NumberTests.swift +++ b/Tests/SwiftyJSONTests/NumberTests.swift @@ -109,12 +109,12 @@ class NumberTests: XCTestCase { json.double = 23231.65 XCTAssertTrue(json.float! == 23231.65) XCTAssertTrue(json.floatValue == 23231.65) - XCTAssertEqual(json.numberValue, NSNumber(value:23231.65)) + XCTAssertEqual(json.numberValue, NSNumber(value: 23231.65)) json.double = -98766.23 XCTAssertEqual(json.float!, -98766.23) XCTAssertEqual(json.floatValue, -98766.23) - XCTAssertEqual(json.numberValue, NSNumber(value:-98766.23)) + XCTAssertEqual(json.numberValue, NSNumber(value: -98766.23)) } func testInt() { diff --git a/Tests/SwiftyJSONTests/PerformanceTests.swift b/Tests/SwiftyJSONTests/PerformanceTests.swift index 72140b54..64de9e14 100644 --- a/Tests/SwiftyJSONTests/PerformanceTests.swift +++ b/Tests/SwiftyJSONTests/PerformanceTests.swift @@ -30,7 +30,7 @@ class PerformanceTests: XCTestCase { override func setUp() { super.setUp() - if let file = Bundle(for:PerformanceTests.self).path(forResource: "Tests", ofType: "json") { + if let file = Bundle(for: PerformanceTests.self).path(forResource: "Tests", ofType: "json") { self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { XCTFail("Can't find the test JSON file") @@ -61,7 +61,7 @@ class PerformanceTests: XCTestCase { } self.measure { for _ in 1...100 { - let object:Any? = json.object + let object: Any? = json.object XCTAssertTrue(object != nil) } } diff --git a/Tests/SwiftyJSONTests/PrintableTests.swift b/Tests/SwiftyJSONTests/PrintableTests.swift index ebecbe1a..ba5863d1 100644 --- a/Tests/SwiftyJSONTests/PrintableTests.swift +++ b/Tests/SwiftyJSONTests/PrintableTests.swift @@ -98,7 +98,7 @@ class PrintableTests: XCTestCase { } func testDictionaryWithStrings() { - let dict = ["foo": "{\"bar\":123}"] as [String : Any] + let dict = ["foo": "{\"bar\":123}"] as [String: Any] let json = JSON(dict) var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") diff --git a/Tests/SwiftyJSONTests/SequenceTypeTests.swift b/Tests/SwiftyJSONTests/SequenceTypeTests.swift index 488ea865..d0d8cadd 100644 --- a/Tests/SwiftyJSONTests/SequenceTypeTests.swift +++ b/Tests/SwiftyJSONTests/SequenceTypeTests.swift @@ -26,7 +26,7 @@ import SwiftyJSON class SequenceTypeTests: XCTestCase { func testJSONFile() { - if let file = Bundle(for:BaseTests.self).path(forResource: "Tests", ofType: "json") { + if let file = Bundle(for: BaseTests.self).path(forResource: "Tests", ofType: "json") { let testData = try? Data(contentsOf: URL(fileURLWithPath: file)) guard let json = try? JSON(data: testData!) else { XCTFail("Unable to parse the data") @@ -127,11 +127,11 @@ class SequenceTypeTests: XCTestCase { index += 1 } XCTAssertEqual(index, 3) - XCTAssertEqual((array[0] as! [String : Int])["1"]!, 1) - XCTAssertEqual((array[0] as! [String : Int])["2"]!, 2) - XCTAssertEqual((array[1] as! [String : String])["a"]!, "A") - XCTAssertEqual((array[1] as! [String : String])["b"]!, "B") - XCTAssertEqual((array[2] as! [String : NSNull])["null"]!, NSNull()) + XCTAssertEqual((array[0] as! [String: Int])["1"]!, 1) + XCTAssertEqual((array[0] as! [String: Int])["2"]!, 2) + XCTAssertEqual((array[1] as! [String: String])["a"]!, "A") + XCTAssertEqual((array[1] as! [String: String])["b"]!, "B") + XCTAssertEqual((array[2] as! [String: NSNull])["null"]!, NSNull()) } func testDictionaryAllNumber() { @@ -204,7 +204,7 @@ class SequenceTypeTests: XCTestCase { } func testDictionaryAllArray() { - var json: JSON = JSON (["Number": [NSNumber(value:1), NSNumber(value:2.123456), NSNumber(value:123456789)], "String": ["aa", "bbb", "cccc"], "Mix": [true, "766", NSNull(), 655231.9823]]) + var json: JSON = JSON (["Number": [NSNumber(value: 1), NSNumber(value: 2.123456), NSNumber(value: 123456789)], "String": ["aa", "bbb", "cccc"], "Mix": [true, "766", NSNull(), 655231.9823]]) XCTAssertEqual(json.count, 3) diff --git a/Tests/SwiftyJSONTests/StringTests.swift b/Tests/SwiftyJSONTests/StringTests.swift index fb226fc5..cde05672 100644 --- a/Tests/SwiftyJSONTests/StringTests.swift +++ b/Tests/SwiftyJSONTests/StringTests.swift @@ -38,7 +38,7 @@ class StringTests: XCTestCase { func testUrl() { let json = JSON("http://github.com") - XCTAssertEqual(json.url!, URL(string:"http://github.com")!) + XCTAssertEqual(json.url!, URL(string: "http://github.com")!) } func testBool() { diff --git a/Tests/SwiftyJSONTests/SubscriptTests.swift b/Tests/SwiftyJSONTests/SubscriptTests.swift index 0673f3a0..5b399f40 100644 --- a/Tests/SwiftyJSONTests/SubscriptTests.swift +++ b/Tests/SwiftyJSONTests/SubscriptTests.swift @@ -163,7 +163,7 @@ class SubscriptTests: XCTestCase { func testDictionaryAllArray() { //Swift bug: [1, 2.01,3.09] is convert to [1, 2, 3] (Array) - let json: JSON = JSON ([[NSNumber(value:1), NSNumber(value:2.123456), NSNumber(value:123456789)], ["aa", "bbb", "cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) + let json: JSON = JSON ([[NSNumber(value: 1), NSNumber(value: 2.123456), NSNumber(value: 123456789)], ["aa", "bbb", "cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) XCTAssertTrue(json[0] == [1, 2.123456, 123456789]) XCTAssertEqual(json[0][1].double!, 2.123456) XCTAssertTrue(json[0][2] == 123456789) @@ -180,7 +180,7 @@ class SubscriptTests: XCTestCase { } func testOutOfBounds() { - let json: JSON = JSON ([[NSNumber(value:1), NSNumber(value:2.123456), NSNumber(value:123456789)], ["aa", "bbb", "cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) + let json: JSON = JSON ([[NSNumber(value: 1), NSNumber(value: 2.123456), NSNumber(value: 123456789)], ["aa", "bbb", "cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) XCTAssertEqual(json[9], JSON.null) XCTAssertEqual(json[-2].error, SwiftyJSONError.indexOutOfBounds) XCTAssertEqual(json[6].error, SwiftyJSONError.indexOutOfBounds) From dd861383ba4f9b7859e378315c5d1b734dcbfe81 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 8 Nov 2017 13:32:30 +0800 Subject: [PATCH 199/260] Add .hound.yml --- .hound.yml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .hound.yml diff --git a/.hound.yml b/.hound.yml new file mode 100644 index 00000000..b867fd9c --- /dev/null +++ b/.hound.yml @@ -0,0 +1,2 @@ +swift: + config_file: .swiftlint.yml From d9682fb9e722fc6aefe664ff7c87ee16a94df4fc Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 8 Nov 2017 17:11:34 +0800 Subject: [PATCH 200/260] Version bump to 4.0.0 --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 76daf480..e5eba227 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "4.0.0-alpha.1" + s.version = "4.0.0" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } From fb67763f27990ba76a42bf412f848af5aef5e5ea Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 8 Nov 2017 03:47:20 -0600 Subject: [PATCH 201/260] Update README.md --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 4681ca9f..3d3e75ef 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,6 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. 5. [Work with Alamofire](#work-with-alamofire) 6. [Work with Moya](#work-with-moya) -> For Legacy Swift support, take a look at the [swift2 branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift2) - > [中文介绍](http://tangplin.github.io/swiftyjson/) @@ -92,7 +90,7 @@ platform :ios, '8.0' use_frameworks! target 'MyApp' do - pod 'SwiftyJSON' + pod 'SwiftyJSON' end ``` From da527cf88a1661ac369bf0df889353c10bee26ae Mon Sep 17 00:00:00 2001 From: Tom Duncalf Date: Tue, 16 Jan 2018 21:54:12 +0100 Subject: [PATCH 202/260] Update README to specify correct JSONSubscriptType --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3d3e75ef..35355ff8 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ let name = json[].string ```swift // With a custom way -let keys:[SubscriptType] = [1,"list",2,"name"] +let keys:[JSONSubscriptType] = [1,"list",2,"name"] let name = json[keys].string ``` From 38d9815729537f18fe09310b839edb622bfb8c08 Mon Sep 17 00:00:00 2001 From: Lei Wang Date: Tue, 9 Jan 2018 21:08:32 +0800 Subject: [PATCH 203/260] Support Codable --- Example/Playground.playground/Contents.swift | 1 - Source/SwiftyJSON.swift | 134 +++++++++++++++++-- SwiftyJSON.xcodeproj/project.pbxproj | 8 ++ Tests/SwiftyJSONTests/CodableTests.swift | 100 ++++++++++++++ 4 files changed, 228 insertions(+), 15 deletions(-) create mode 100644 Tests/SwiftyJSONTests/CodableTests.swift diff --git a/Example/Playground.playground/Contents.swift b/Example/Playground.playground/Contents.swift index 134a640c..9306d850 100644 --- a/Example/Playground.playground/Contents.swift +++ b/Example/Playground.playground/Contents.swift @@ -413,4 +413,3 @@ let stringRepresentionJson: JSON = JSON(stringRepresentationDict) let representation = stringRepresentionJson.rawString([.castNilToNSNull: true]) print(representation!) // representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} - diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index 312763e4..f3553fe5 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -545,53 +545,50 @@ extension JSON { extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { - self.init(value as Any) + self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { - self.init(value as Any) + self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { - self.init(value as Any) + self.init(value) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { - self.init(value as Any) + self.init(value) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { - self.init(value as Any) + self.init(value) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { - self.init(value as Any) + self.init(value) } } extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { - var dictionary = [String: Any](minimumCapacity: elements.count) - for (k, v) in elements { - dictionary[k] = v - } - self.init(dictionary as Any) + let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1}) + self.init(dictionary) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { - self.init(elements as Any) + self.init(elements) } } @@ -776,7 +773,7 @@ extension JSON { } set { if let array = newValue { - self.object = array as Any + self.object = array } else { self.object = NSNull() } @@ -819,7 +816,7 @@ extension JSON { } set { if let v = newValue { - self.object = v as Any + self.object = v } else { self.object = NSNull() } @@ -1455,3 +1452,112 @@ public enum writingOptionsKeys { case maxObjextDepth case encoding } + +// MARK: - JSON: Codable +extension JSON: Codable { + private static var codableTypes: [Codable.Type] { + return [ + Bool.self, + Int.self, + Int8.self, + Int16.self, + Int32.self, + Int64.self, + UInt.self, + UInt8.self, + UInt16.self, + UInt32.self, + UInt64.self, + Double.self, + String.self, + [JSON].self, + [String: JSON].self + ] + } + public init(from decoder: Decoder) throws { + var object: Any? + + if let container = try? decoder.singleValueContainer(), !container.decodeNil() { + for type in JSON.codableTypes { + if object != nil { + break + } + // try to decode value + switch type { + case let boolType as Bool.Type: + object = try? container.decode(boolType) + case let intType as Int.Type: + object = try? container.decode(intType) + case let int8Type as Int8.Type: + object = try? container.decode(int8Type) + case let int32Type as Int32.Type: + object = try? container.decode(int32Type) + case let int64Type as Int64.Type: + object = try? container.decode(int64Type) + case let uintType as UInt.Type: + object = try? container.decode(uintType) + case let uint8Type as UInt8.Type: + object = try? container.decode(uint8Type) + case let uint16Type as UInt16.Type: + object = try? container.decode(uint16Type) + case let uint32Type as UInt32.Type: + object = try? container.decode(uint32Type) + case let uint64Type as UInt64.Type: + object = try? container.decode(uint64Type) + case let doubleType as Double.Type: + object = try? container.decode(doubleType) + case let stringType as String.Type: + object = try? container.decode(stringType) + case let jsonValueArrayType as [JSON].Type: + object = try? container.decode(jsonValueArrayType) + case let jsonValueDictType as [String: JSON].Type: + object = try? container.decode(jsonValueDictType) + default: + break + } + } + } + self.init(object ?? NSNull()) + } + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + if object is NSNull { + try container.encodeNil() + return + } + switch object { + case let intValue as Int: + try container.encode(intValue) + case let int8Value as Int8: + try container.encode(int8Value) + case let int32Value as Int32: + try container.encode(int32Value) + case let int64Value as Int64: + try container.encode(int64Value) + case let uintValue as UInt: + try container.encode(uintValue) + case let uint8Value as UInt8: + try container.encode(uint8Value) + case let uint16Value as UInt16: + try container.encode(uint16Value) + case let uint32Value as UInt32: + try container.encode(uint32Value) + case let uint64Value as UInt64: + try container.encode(uint64Value) + case let doubleValue as Double: + try container.encode(doubleValue) + case let boolValue as Bool: + try container.encode(boolValue) + case let stringValue as String: + try container.encode(stringValue) + case is [Any]: + let jsonValueArray = array ?? [] + try container.encode(jsonValueArray) + case is [String: Any]: + let jsonValueDictValue = dictionary ?? [:] + try container.encode(jsonValueDictValue) + default: + break + } + } +} diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 32d607b2..494fb964 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -29,6 +29,9 @@ 5DD502911D9B21810004C112 /* NestedJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD502901D9B21810004C112 /* NestedJSONTests.swift */; }; 5DD502921D9B21810004C112 /* NestedJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD502901D9B21810004C112 /* NestedJSONTests.swift */; }; 5DD502931D9B21810004C112 /* NestedJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD502901D9B21810004C112 /* NestedJSONTests.swift */; }; + 712921EF2004E4EB00DA6340 /* CodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 712921EE2004E4EB00DA6340 /* CodableTests.swift */; }; + 712921F02004E4EB00DA6340 /* CodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 712921EE2004E4EB00DA6340 /* CodableTests.swift */; }; + 712921F12004E4EB00DA6340 /* CodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 712921EE2004E4EB00DA6340 /* CodableTests.swift */; }; 7236B4EE1BAC14150020529B /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8491E1D19CD6DAE00CCFAE6 /* SwiftyJSON.swift */; }; 7236B4F11BAC14150020529B /* SwiftyJSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E4FEFE019575BE100351305 /* SwiftyJSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; 9C459EF41A910334008C9A41 /* SwiftyJSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E4FEFE019575BE100351305 /* SwiftyJSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -117,6 +120,7 @@ 2E4FEFE019575BE100351305 /* SwiftyJSON.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SwiftyJSON.h; sourceTree = ""; }; 2E4FEFE619575BE100351305 /* SwiftyJSON iOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON iOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; 5DD502901D9B21810004C112 /* NestedJSONTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NestedJSONTests.swift; sourceTree = ""; }; + 712921EE2004E4EB00DA6340 /* CodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodableTests.swift; sourceTree = ""; }; 7236B4F61BAC14150020529B /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 7236B4F71BAC14150020529B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-tvOS.plist"; sourceTree = ""; }; 9C459EF61A9103B1008C9A41 /* Info-macOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Info-macOS.plist"; sourceTree = ""; }; @@ -265,6 +269,7 @@ A8B66C8B19E51D6500540692 /* DictionaryTests.swift */, A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */, A8B66C8D19E52F4200540692 /* ArrayTests.swift */, + 712921EE2004E4EB00DA6340 /* CodableTests.swift */, 2E4FEFEB19575BE100351305 /* Supporting Files */, ); name = SwiftyJSONTests; @@ -604,6 +609,7 @@ A819C49F19E2EE5B00ADCC3D /* SubscriptTests.swift in Sources */, A830A6951E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */, A863BE2819EED46F0092A41F /* RawTests.swift in Sources */, + 712921EF2004E4EB00DA6340 /* CodableTests.swift in Sources */, A885D1D219CF1EE6002FD4C3 /* BaseTests.swift in Sources */, A8B66C8E19E52F4200540692 /* ArrayTests.swift in Sources */, A8B66C8C19E51D6500540692 /* DictionaryTests.swift in Sources */, @@ -643,6 +649,7 @@ 9C459EFA1A9103C1008C9A41 /* BaseTests.swift in Sources */, A830A6961E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */, 9C459F041A9103C1008C9A41 /* DictionaryTests.swift in Sources */, + 712921F02004E4EB00DA6340 /* CodableTests.swift in Sources */, 9C459EF91A9103C1008C9A41 /* PerformanceTests.swift in Sources */, 9C459EFE1A9103C1008C9A41 /* LiteralConvertibleTests.swift in Sources */, 9C459EFC1A9103C1008C9A41 /* PrintableTests.swift in Sources */, @@ -666,6 +673,7 @@ A8580F841BCF69A000DA927B /* SubscriptTests.swift in Sources */, A830A6971E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */, A8580F851BCF69A000DA927B /* LiteralConvertibleTests.swift in Sources */, + 712921F12004E4EB00DA6340 /* CodableTests.swift in Sources */, A8580F861BCF69A000DA927B /* RawRepresentableTests.swift in Sources */, A8580F871BCF69A000DA927B /* ComparableTests.swift in Sources */, A8580F881BCF69A000DA927B /* StringTests.swift in Sources */, diff --git a/Tests/SwiftyJSONTests/CodableTests.swift b/Tests/SwiftyJSONTests/CodableTests.swift new file mode 100644 index 00000000..9cc43eaa --- /dev/null +++ b/Tests/SwiftyJSONTests/CodableTests.swift @@ -0,0 +1,100 @@ +// CodableTests.swift +// +// Created by Lei Wang on 2018/1/9. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import XCTest +import SwiftyJSON + +class CodableTests: XCTestCase { + + func testEncodeNull() { + var json = JSON([NSNull()]) + _ = try! JSONEncoder().encode(json) + json = JSON([nil]) + _ = try! JSONEncoder().encode(json) + let dictionary: [String: Any?] = ["key": nil] + json = JSON(dictionary) + _ = try! JSONEncoder().encode(json) + } + func testArrayCodable() { + let jsonString = """ + [1,"false", ["A", 4.3231],"3",true] + """ + var data = jsonString.data(using: .utf8)! + let json = try! JSONDecoder().decode(JSON.self, from: data) + XCTAssertEqual(json.arrayValue.first?.int, 1) + XCTAssertEqual(json[1].bool, nil) + XCTAssertEqual(json[1].string, "false") + XCTAssertEqual(json[3].string, "3") + XCTAssertEqual(json[2][1].double!, 4.3231) + XCTAssertEqual(json.arrayValue[0].bool, nil) + XCTAssertEqual(json.array!.last!.bool, true) + let jsonList = try! JSONDecoder().decode([JSON].self, from: data) + XCTAssertEqual(jsonList.first?.int, 1) + XCTAssertEqual(jsonList.last!.bool, true) + data = try! JSONEncoder().encode(json) + let list = try! JSONSerialization.jsonObject(with: data, options: []) as! [Any] + XCTAssertEqual(list[0] as! Int, 1) + XCTAssertEqual((list[2] as! [Any])[1] as! Float, 4.3231) + } + func testDictionaryCodable() { + let dictionary: [String: Any] = ["number": 9823.212, "name": "NAME", "list": [1234, 4.21223256], "object": ["sub_number": 877.2323, "sub_name": "sub_name"], "bool": true] + var data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) + let json = try! JSONDecoder().decode(JSON.self, from: data) + XCTAssertNotNil(json.dictionary) + XCTAssertEqual(json["number"].float, 9823.212) + XCTAssertEqual(json["list"].arrayObject is [Float], true) + XCTAssertEqual(json["object"]["sub_number"].float, 877.2323) + XCTAssertEqual(json["bool"].bool, true) + let jsonDict = try! JSONDecoder().decode([String: JSON].self, from: data) + XCTAssertEqual(jsonDict["number"]?.int, 9823) + XCTAssertEqual(jsonDict["object"]?["sub_name"], "sub_name") + data = try! JSONEncoder().encode(json) + var encoderDict = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] + XCTAssertEqual(encoderDict["list"] as! [Float], [1234, 4.21223256]) + XCTAssertEqual(encoderDict["bool"] as! Bool, true) + data = try! JSONEncoder().encode(jsonDict) + encoderDict = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] + XCTAssertEqual(encoderDict["name"] as! String, dictionary["name"] as! String) + XCTAssertEqual((encoderDict["object"] as! [String: Any])["sub_number"] as! Float, 877.2323) + } + func testCodableModel() { + struct CodableModel: Codable { + let name: String + let number: Double + let bool: Bool + let list: [Double] + private let object: JSON + var subName: String? { + return object["sub_name"].string + } + } + let dictionary: [String: Any] = [ + "number": 9823.212, + "name": "NAME", + "list": [1234, 4.21223256], + "object": ["sub_number": 877.2323, "sub_name": "sub_name"], + "bool": true] + let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) + let model = try! JSONDecoder().decode(CodableModel.self, from: data) + XCTAssertEqual(model.subName, "sub_name") + } +} From 481ba1eb19f2efdbf58b7f3daf2bf4ad9d1291dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ota=CC=81vio=20Lima?= Date: Wed, 28 Mar 2018 20:33:17 +0300 Subject: [PATCH 204/260] Add String to .boolValue tests for "Yes" and "1" --- Tests/SwiftyJSONTests/StringTests.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Tests/SwiftyJSONTests/StringTests.swift b/Tests/SwiftyJSONTests/StringTests.swift index cde05672..9ce10643 100644 --- a/Tests/SwiftyJSONTests/StringTests.swift +++ b/Tests/SwiftyJSONTests/StringTests.swift @@ -56,6 +56,16 @@ class StringTests: XCTestCase { XCTAssertTrue(json.boolValue) } + func testBoolWithYes() { + let json = JSON("Yes") + XCTAssertTrue(json.boolValue) + } + + func testBoolWith1() { + let json = JSON("1") + XCTAssertTrue(json.boolValue) + } + func testUrlPercentEscapes() { let emDash = "\\u2014" let urlString = "http://examble.com/unencoded" + emDash + "string" From bbd9abff2c86a65ea6d63eaf526eb7dc0cac0aa0 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 11 Apr 2018 01:01:17 +0800 Subject: [PATCH 205/260] Improve broken testcases --- Tests/SwiftyJSONTests/CodableTests.swift | 34 +++++++++++-------- .../RawRepresentableTests.swift | 4 ++- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/Tests/SwiftyJSONTests/CodableTests.swift b/Tests/SwiftyJSONTests/CodableTests.swift index 9cc43eaa..a3608c1c 100644 --- a/Tests/SwiftyJSONTests/CodableTests.swift +++ b/Tests/SwiftyJSONTests/CodableTests.swift @@ -24,7 +24,7 @@ import XCTest import SwiftyJSON class CodableTests: XCTestCase { - + func testEncodeNull() { var json = JSON([NSNull()]) _ = try! JSONEncoder().encode(json) @@ -34,6 +34,7 @@ class CodableTests: XCTestCase { json = JSON(dictionary) _ = try! JSONEncoder().encode(json) } + func testArrayCodable() { let jsonString = """ [1,"false", ["A", 4.3231],"3",true] @@ -53,15 +54,16 @@ class CodableTests: XCTestCase { data = try! JSONEncoder().encode(json) let list = try! JSONSerialization.jsonObject(with: data, options: []) as! [Any] XCTAssertEqual(list[0] as! Int, 1) - XCTAssertEqual((list[2] as! [Any])[1] as! Float, 4.3231) + XCTAssertEqual((list[2] as! [Any])[1] as! NSNumber, 4.3231) } + func testDictionaryCodable() { let dictionary: [String: Any] = ["number": 9823.212, "name": "NAME", "list": [1234, 4.21223256], "object": ["sub_number": 877.2323, "sub_name": "sub_name"], "bool": true] var data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) let json = try! JSONDecoder().decode(JSON.self, from: data) XCTAssertNotNil(json.dictionary) XCTAssertEqual(json["number"].float, 9823.212) - XCTAssertEqual(json["list"].arrayObject is [Float], true) + XCTAssertEqual(json["list"].arrayObject is [NSNumber], true) XCTAssertEqual(json["object"]["sub_number"].float, 877.2323) XCTAssertEqual(json["bool"].bool, true) let jsonDict = try! JSONDecoder().decode([String: JSON].self, from: data) @@ -69,24 +71,15 @@ class CodableTests: XCTestCase { XCTAssertEqual(jsonDict["object"]?["sub_name"], "sub_name") data = try! JSONEncoder().encode(json) var encoderDict = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] - XCTAssertEqual(encoderDict["list"] as! [Float], [1234, 4.21223256]) + XCTAssertEqual(encoderDict["list"] as! [NSNumber], [1234, 4.21223256]) XCTAssertEqual(encoderDict["bool"] as! Bool, true) data = try! JSONEncoder().encode(jsonDict) encoderDict = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] XCTAssertEqual(encoderDict["name"] as! String, dictionary["name"] as! String) - XCTAssertEqual((encoderDict["object"] as! [String: Any])["sub_number"] as! Float, 877.2323) + XCTAssertEqual((encoderDict["object"] as! [String: Any])["sub_number"] as! NSNumber, 877.2323) } + func testCodableModel() { - struct CodableModel: Codable { - let name: String - let number: Double - let bool: Bool - let list: [Double] - private let object: JSON - var subName: String? { - return object["sub_name"].string - } - } let dictionary: [String: Any] = [ "number": 9823.212, "name": "NAME", @@ -98,3 +91,14 @@ class CodableTests: XCTestCase { XCTAssertEqual(model.subName, "sub_name") } } + +private struct CodableModel: Codable { + let name: String + let number: Double + let bool: Bool + let list: [Double] + private let object: JSON + var subName: String? { + return object["sub_name"].string + } +} diff --git a/Tests/SwiftyJSONTests/RawRepresentableTests.swift b/Tests/SwiftyJSONTests/RawRepresentableTests.swift index fec52512..9c628a05 100644 --- a/Tests/SwiftyJSONTests/RawRepresentableTests.swift +++ b/Tests/SwiftyJSONTests/RawRepresentableTests.swift @@ -39,7 +39,9 @@ class RawRepresentableTests: XCTestCase { XCTAssertEqual(int, 948394394) } XCTAssertEqual(object as? Double, 948394394.347384) - XCTAssertEqual(object as? Float, 948394394.347384) + if let float = object as? Float { + XCTAssertEqual(float, 948394394.347384) + } XCTAssertEqual(object as? NSNumber, 948394394.347384) } From 42c3848afc684baf0f341ea9265ddddf8af3a5c0 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 11 Apr 2018 01:01:52 +0800 Subject: [PATCH 206/260] Update to Xcode 9.3 recommend settings --- Example/Example.xcodeproj/project.pbxproj | 6 +++++- SwiftyJSON.xcodeproj/project.pbxproj | 10 +++++++--- .../xcshareddata/xcschemes/SwiftyJSON iOS.xcscheme | 4 +--- .../xcshareddata/xcschemes/SwiftyJSON macOS.xcscheme | 4 +--- .../xcshareddata/xcschemes/SwiftyJSON tvOS.xcscheme | 4 +--- .../xcshareddata/xcschemes/SwiftyJSON watchOS.xcscheme | 4 +--- .../xcshareddata/IDEWorkspaceChecks.plist | 8 ++++++++ 7 files changed, 24 insertions(+), 16 deletions(-) create mode 100644 SwiftyJSON.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index 9abea6d6..27cdfe91 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -124,7 +124,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0700; - LastUpgradeCheck = 0900; + LastUpgradeCheck = 0930; ORGANIZATIONNAME = swiftyjson; TargetAttributes = { A82A1C1819D926B8009A653D = { @@ -210,12 +210,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -264,12 +266,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 494fb964..2b3c99a5 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -457,7 +457,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0710; - LastUpgradeCheck = 0900; + LastUpgradeCheck = 0930; TargetAttributes = { 2E4FEFDA19575BE100351305 = { CreatedOnToolsVersion = 6.0; @@ -725,12 +725,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -783,12 +785,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -1062,7 +1066,7 @@ isa = XCBuildConfiguration; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = macosx10.13; + SDKROOT = macosx; }; name = Debug; }; @@ -1070,7 +1074,7 @@ isa = XCBuildConfiguration; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = macosx10.13; + SDKROOT = macosx; }; name = Release; }; diff --git a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON iOS.xcscheme b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON iOS.xcscheme index 61b7bfb3..98076542 100644 --- a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON iOS.xcscheme +++ b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON iOS.xcscheme @@ -1,6 +1,6 @@ @@ -37,7 +36,6 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" diff --git a/SwiftyJSON.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/SwiftyJSON.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/SwiftyJSON.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + From 1284c0619d8d8cff3d0ea57beed0614a3980b960 Mon Sep 17 00:00:00 2001 From: Bojan Stefanovic Date: Tue, 10 Apr 2018 10:10:05 -0700 Subject: [PATCH 207/260] Updated broken Twitter API link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35355ff8..15758050 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. -Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline). +Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline). The code would look like this: From f2126db35c1142b9c9028a69d04dde67f17562e8 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 11 Apr 2018 10:30:57 +0800 Subject: [PATCH 208/260] Update README.md --- README.md | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 15758050..32749799 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. -Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline). +Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to [Twitter's API](https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline)). The code would look like this: @@ -90,38 +90,36 @@ platform :ios, '8.0' use_frameworks! target 'MyApp' do - pod 'SwiftyJSON' + pod 'SwiftyJSON', '~> 4.0' end ``` -Note that this requires CocoaPods version 36, and your iOS deployment target to be at least 8.0: - - #### Carthage (iOS 8+, OS X 10.9+) You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: ``` -github "SwiftyJSON/SwiftyJSON" +github "SwiftyJSON/SwiftyJSON" ~> 4.0 ``` +If you use Carthage to build your dependencies, make sure you have added `SwiftyJSON.framework` to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase. + #### Swift Package Manager You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: ```swift +// swift-tools-version:4.0 import PackageDescription let package = Package( name: "YOUR_PROJECT_NAME", - targets: [], dependencies: [ - .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1, 0, 0).. Date: Wed, 11 Apr 2018 10:48:01 +0800 Subject: [PATCH 209/260] Update osx image to 9.3 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 570a6014..cbc39370 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: objective-c -osx_image: xcode9 +osx_image: xcode9.3 xcode_sdk: iphonesimulator10.0 script: - set -o pipefail From 1968e3bd1d64744099e21e4e774b3cdc5e926abd Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Fri, 13 Apr 2018 01:10:02 +0800 Subject: [PATCH 210/260] Xcode9.3 image no longer support Apple TV 1080p --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index cbc39370..e94149f3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,4 +5,4 @@ script: - set -o pipefail - travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON iOS" -destination "platform=iOS Simulator,name=iPhone 6" build-for-testing test | xcpretty - travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON macOS" build-for-testing test | xcpretty -- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON tvOS" -destination "platform=tvOS Simulator,name=Apple TV 1080p" build-for-testing test | xcpretty +- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON tvOS" -destination "platform=tvOS Simulator,name=Apple TV" build-for-testing test | xcpretty From ebfc0d7e314f15c1df02fcb198beb40624421839 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 18 Apr 2018 23:41:35 +0800 Subject: [PATCH 211/260] Version bump to 4.1.0 --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index e5eba227..3b442264 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "4.0.0" + s.version = "4.1.0" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } From 454458d12752b19dfe47d7b0a43870cc66e63b2a Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 9 May 2018 00:58:19 +0800 Subject: [PATCH 212/260] Update Xcode Settings --- Example/Example.xcodeproj/project.pbxproj | 8 +++++--- SwiftyJSON.xcodeproj/project.pbxproj | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index 27cdfe91..95a703b4 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -129,7 +129,7 @@ TargetAttributes = { A82A1C1819D926B8009A653D = { CreatedOnToolsVersion = 6.0.1; - LastSwiftMigration = 0820; + LastSwiftMigration = 0930; ProvisioningStyle = Manual; }; }; @@ -313,7 +313,8 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 3.0; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; }; name = Debug; }; @@ -328,7 +329,8 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 3.0; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; }; name = Release; }; diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 2b3c99a5..e290e728 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -479,6 +479,7 @@ }; 9C7DFC641A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; + LastSwiftMigration = 0930; }; A81D162B1E5743B000C62C5F = { CreatedOnToolsVersion = 8.2.1; @@ -486,6 +487,7 @@ }; A8580F731BCF5C5B00DA927B = { CreatedOnToolsVersion = 7.1; + LastSwiftMigration = 0930; }; E4D7CCDE1B9465A700EE7221 = { ProvisioningStyle = Automatic; @@ -936,6 +938,7 @@ SDKROOT = appletvos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = 3; TVOS_DEPLOYMENT_TARGET = 9.0; }; @@ -961,6 +964,7 @@ PRODUCT_NAME = SwiftyJSON; SDKROOT = appletvos; SKIP_INSTALL = YES; + SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = 3; TVOS_DEPLOYMENT_TARGET = 9.0; }; @@ -993,6 +997,7 @@ SDKROOT = macosx; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.0; }; name = Debug; }; @@ -1019,6 +1024,7 @@ PRODUCT_NAME = "$(PROJECT_NAME)"; SDKROOT = macosx; SKIP_INSTALL = YES; + SWIFT_VERSION = 4.0; }; name = Release; }; @@ -1041,6 +1047,8 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; }; name = Debug; }; @@ -1059,6 +1067,8 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; }; name = Release; }; @@ -1092,6 +1102,8 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; TVOS_DEPLOYMENT_TARGET = 9.0; }; name = Debug; @@ -1110,6 +1122,8 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.tangplin.SwiftyJSON-tvOS-Tests"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; + SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_VERSION = 4.0; TVOS_DEPLOYMENT_TARGET = 9.0; }; name = Release; @@ -1136,6 +1150,7 @@ SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = 4; WATCHOS_DEPLOYMENT_TARGET = 2.0; }; @@ -1162,6 +1177,7 @@ SDKROOT = watchos; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos"; + SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = 4; WATCHOS_DEPLOYMENT_TARGET = 2.0; }; From 05e40f8b1240e44f2357086cc69185f1692a1d3d Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 18 Sep 2018 13:11:05 +0800 Subject: [PATCH 213/260] Update build settings to Xcode 10.0 --- Example/Example.xcodeproj/project.pbxproj | 4 +-- SwiftyJSON.xcodeproj/project.pbxproj | 31 +++++++++++------------ 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index 95a703b4..54e81356 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -313,7 +313,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; SWIFT_VERSION = 4.0; }; name = Debug; @@ -329,7 +329,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_SWIFT3_OBJC_INFERENCE = On; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; SWIFT_VERSION = 4.0; }; name = Release; diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index e290e728..16ccac87 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -471,15 +471,17 @@ TestTargetID = 2E4FEFDA19575BE100351305; }; 7236B4EC1BAC14150020529B = { + LastSwiftMigration = 1000; ProvisioningStyle = Automatic; }; 9C7DFC5A1A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; + LastSwiftMigration = 1000; ProvisioningStyle = Automatic; }; 9C7DFC641A9102BD005AA3F7 = { CreatedOnToolsVersion = 6.1.1; - LastSwiftMigration = 0930; + LastSwiftMigration = 1000; }; A81D162B1E5743B000C62C5F = { CreatedOnToolsVersion = 8.2.1; @@ -487,9 +489,10 @@ }; A8580F731BCF5C5B00DA927B = { CreatedOnToolsVersion = 7.1; - LastSwiftMigration = 0930; + LastSwiftMigration = 1000; }; E4D7CCDE1B9465A700EE7221 = { + LastSwiftMigration = 1000; ProvisioningStyle = Automatic; }; }; @@ -938,7 +941,7 @@ SDKROOT = appletvos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = 3; TVOS_DEPLOYMENT_TARGET = 9.0; }; @@ -964,7 +967,7 @@ PRODUCT_NAME = SwiftyJSON; SDKROOT = appletvos; SKIP_INSTALL = YES; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = 3; TVOS_DEPLOYMENT_TARGET = 9.0; }; @@ -997,7 +1000,7 @@ SDKROOT = macosx; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; }; name = Debug; }; @@ -1024,7 +1027,7 @@ PRODUCT_NAME = "$(PROJECT_NAME)"; SDKROOT = macosx; SKIP_INSTALL = YES; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; }; name = Release; }; @@ -1047,8 +1050,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_SWIFT3_OBJC_INFERENCE = On; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; }; name = Debug; }; @@ -1067,8 +1069,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_SWIFT3_OBJC_INFERENCE = On; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; }; name = Release; }; @@ -1102,8 +1103,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_SWIFT3_OBJC_INFERENCE = On; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; TVOS_DEPLOYMENT_TARGET = 9.0; }; name = Debug; @@ -1122,8 +1122,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.tangplin.SwiftyJSON-tvOS-Tests"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; - SWIFT_SWIFT3_OBJC_INFERENCE = On; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; TVOS_DEPLOYMENT_TARGET = 9.0; }; name = Release; @@ -1150,7 +1149,7 @@ SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = 4; WATCHOS_DEPLOYMENT_TARGET = 2.0; }; @@ -1177,7 +1176,7 @@ SDKROOT = watchos; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = 4; WATCHOS_DEPLOYMENT_TARGET = 2.0; }; From 1f37a67c6163be2561aaa1854cb921c54d1ad73c Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 18 Sep 2018 13:13:56 +0800 Subject: [PATCH 214/260] Update CI to Xcode 10.0/iOS 12.0 --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index e94149f3..831af979 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: objective-c -osx_image: xcode9.3 -xcode_sdk: iphonesimulator10.0 +osx_image: xcode10.0 +xcode_sdk: iphonesimulator12.0 script: - set -o pipefail - travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON iOS" -destination "platform=iOS Simulator,name=iPhone 6" build-for-testing test | xcpretty From 44dc2dc7f28b0485876c9280b0dfda93ff6fcbeb Mon Sep 17 00:00:00 2001 From: Quentin Dreyer Date: Tue, 21 Aug 2018 16:06:51 +0200 Subject: [PATCH 215/260] Added swift_version to podspec --- SwiftyJSON.podspec | 1 + 1 file changed, 1 insertion(+) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 3b442264..00434ddb 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -7,6 +7,7 @@ Pod::Spec.new do |s| s.authors = { "lingoer" => "lingoerer@gmail.com", "tangplin" => "tangplin@gmail.com" } s.requires_arc = true + s.swift_version = "4.2" s.osx.deployment_target = "10.9" s.ios.deployment_target = "8.0" s.watchos.deployment_target = "2.0" From cd8ea07d5b44673fbf882e535bc3102e05858d34 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 25 Sep 2018 23:14:26 +0800 Subject: [PATCH 216/260] Fix version --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 831af979..34acdea7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: objective-c -osx_image: xcode10.0 +osx_image: xcode10 xcode_sdk: iphonesimulator12.0 script: - set -o pipefail From 747a29f8d9e85448b231d8f34d5eac29e664774c Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 25 Sep 2018 23:22:01 +0800 Subject: [PATCH 217/260] Update min requirement of watchOS to 3.0 --- SwiftyJSON.podspec | 2 +- SwiftyJSON.xcodeproj/project.pbxproj | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 3b442264..b1cdf26f 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -9,7 +9,7 @@ Pod::Spec.new do |s| s.requires_arc = true s.osx.deployment_target = "10.9" s.ios.deployment_target = "8.0" - s.watchos.deployment_target = "2.0" + s.watchos.deployment_target = "3.0" s.tvos.deployment_target = "9.0" s.source = { :git => "https://github.com/SwiftyJSON/SwiftyJSON.git", :tag => s.version } s.source_files = "Source/*.swift" diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 16ccac87..1ec04ff6 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -1151,7 +1151,7 @@ SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = 4; - WATCHOS_DEPLOYMENT_TARGET = 2.0; + WATCHOS_DEPLOYMENT_TARGET = 3.0; }; name = Debug; }; @@ -1178,7 +1178,7 @@ SUPPORTED_PLATFORMS = "watchsimulator watchos"; SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = 4; - WATCHOS_DEPLOYMENT_TARGET = 2.0; + WATCHOS_DEPLOYMENT_TARGET = 3.0; }; name = Release; }; From 3451da4ea3f835bb9e0113afdabc4a69605cf44b Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 25 Sep 2018 23:39:29 +0800 Subject: [PATCH 218/260] Version bump to 4.2.0 --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 4d7e6ccf..d5fbc3d1 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "4.1.0" + s.version = "4.2.0" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } From b51eb540e5b4351628f91a50d34385fe73e2c659 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 25 Sep 2018 23:48:52 +0800 Subject: [PATCH 219/260] Remove .swift-version file --- .swift-version | 1 - 1 file changed, 1 deletion(-) delete mode 100644 .swift-version diff --git a/.swift-version b/.swift-version deleted file mode 100644 index 9f55b2cc..00000000 --- a/.swift-version +++ /dev/null @@ -1 +0,0 @@ -3.0 From 184c6884998c41f71a73c459f9b525b7121be846 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 26 Sep 2018 00:20:01 +0800 Subject: [PATCH 220/260] Remove deprecated API in 4.2.0 --- Source/SwiftyJSON.swift | 37 -------------------- Tests/SwiftyJSONTests/PerformanceTests.swift | 2 +- 2 files changed, 1 insertion(+), 38 deletions(-) diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON.swift index f3553fe5..a6c1f3a6 100644 --- a/Source/SwiftyJSON.swift +++ b/Source/SwiftyJSON.swift @@ -24,22 +24,6 @@ import Foundation // MARK: - Error // swiftlint:disable line_length -/// Error domain -@available(*, deprecated, message: "ErrorDomain is deprecated. Use `SwiftyJSONError.errorDomain` instead.", renamed: "SwiftyJSONError.errorDomain") -public let ErrorDomain: String = "SwiftyJSONErrorDomain" - -/// Error code -@available(*, deprecated, message: "ErrorUnsupportedType is deprecated. Use `SwiftyJSONError.unsupportedType` instead.", renamed: "SwiftyJSONError.unsupportedType") -public let ErrorUnsupportedType: Int = 999 -@available(*, deprecated, message: "ErrorIndexOutOfBounds is deprecated. Use `SwiftyJSONError.indexOutOfBounds` instead.", renamed: "SwiftyJSONError.indexOutOfBounds") -public let ErrorIndexOutOfBounds: Int = 900 -@available(*, deprecated, message: "ErrorWrongType is deprecated. Use `SwiftyJSONError.wrongType` instead.", renamed: "SwiftyJSONError.wrongType") -public let ErrorWrongType: Int = 901 -@available(*, deprecated, message: "ErrorNotExist is deprecated. Use `SwiftyJSONError.notExist` instead.", renamed: "SwiftyJSONError.notExist") -public let ErrorNotExist: Int = 500 -@available(*, deprecated, message: "ErrorInvalidJSON is deprecated. Use `SwiftyJSONError.invalidJSON` instead.", renamed: "SwiftyJSONError.invalidJSON") -public let ErrorInvalidJSON: Int = 490 - public enum SwiftyJSONError: Int, Swift.Error { case unsupportedType = 999 case indexOutOfBounds = 900 @@ -146,19 +130,6 @@ public struct JSON { } } - /** - Creates a JSON from JSON string - - - parameter json: Normal json string like '{"a":"b"}' - - - returns: The created JSON - */ - @available(*, deprecated, message: "Use instead `init(parseJSON: )`") - public static func parse(_ json: String) -> JSON { - return json.data(using: String.Encoding.utf8) - .flatMap { try? JSON(data: $0) } ?? JSON(NSNull()) - } - /** Creates a JSON using the object. @@ -592,14 +563,6 @@ extension JSON: Swift.ExpressibleByArrayLiteral { } } -extension JSON: Swift.ExpressibleByNilLiteral { - - @available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions") - public init(nilLiteral: ()) { - self.init(NSNull() as Any) - } -} - // MARK: - Raw extension JSON: Swift.RawRepresentable { diff --git a/Tests/SwiftyJSONTests/PerformanceTests.swift b/Tests/SwiftyJSONTests/PerformanceTests.swift index 64de9e14..7535f7d8 100644 --- a/Tests/SwiftyJSONTests/PerformanceTests.swift +++ b/Tests/SwiftyJSONTests/PerformanceTests.swift @@ -127,7 +127,7 @@ class PerformanceTests: XCTestCase { self.measure { autoreleasepool { if let dictionary = json.dictionary { - XCTAssertTrue(dictionary.count > 0) + XCTAssertTrue(dictionary.count == 100001) } else { XCTFail("dictionary should not be nil") } From 32413d7055cf8f5dce334dd687e9b4323dc21437 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 26 Sep 2018 12:20:00 +0800 Subject: [PATCH 221/260] Re-organize directories --- SwiftyJSON.xcodeproj/project.pbxproj | 62 +++++++++---------- Tests/{SwiftyJSONTests => }/ArrayTests.swift | 0 Tests/{SwiftyJSONTests => }/BaseTests.swift | 0 .../{SwiftyJSONTests => }/CodableTests.swift | 0 .../ComparableTests.swift | 0 .../DictionaryTests.swift | 0 Tests/{SwiftyJSONTests => }/Info-iOS.plist | 0 Tests/{SwiftyJSONTests => }/Info-macOS.plist | 0 Tests/{SwiftyJSONTests => }/Info-tvOS.plist | 0 .../LiteralConvertibleTests.swift | 0 Tests/{SwiftyJSONTests => }/MergeTests.swift | 0 .../MutabilityTests.swift | 0 .../NestedJSONTests.swift | 0 Tests/{SwiftyJSONTests => }/NumberTests.swift | 0 .../PerformanceTests.swift | 0 .../PrintableTests.swift | 0 .../RawRepresentableTests.swift | 0 Tests/{SwiftyJSONTests => }/RawTests.swift | 0 .../SequenceTypeTests.swift | 0 Tests/{SwiftyJSONTests => }/StringTests.swift | 0 .../SubscriptTests.swift | 0 Tests/{SwiftyJSONTests => Tes}/Tests.json | 0 22 files changed, 31 insertions(+), 31 deletions(-) rename Tests/{SwiftyJSONTests => }/ArrayTests.swift (100%) rename Tests/{SwiftyJSONTests => }/BaseTests.swift (100%) rename Tests/{SwiftyJSONTests => }/CodableTests.swift (100%) rename Tests/{SwiftyJSONTests => }/ComparableTests.swift (100%) rename Tests/{SwiftyJSONTests => }/DictionaryTests.swift (100%) rename Tests/{SwiftyJSONTests => }/Info-iOS.plist (100%) rename Tests/{SwiftyJSONTests => }/Info-macOS.plist (100%) rename Tests/{SwiftyJSONTests => }/Info-tvOS.plist (100%) rename Tests/{SwiftyJSONTests => }/LiteralConvertibleTests.swift (100%) rename Tests/{SwiftyJSONTests => }/MergeTests.swift (100%) rename Tests/{SwiftyJSONTests => }/MutabilityTests.swift (100%) rename Tests/{SwiftyJSONTests => }/NestedJSONTests.swift (100%) rename Tests/{SwiftyJSONTests => }/NumberTests.swift (100%) rename Tests/{SwiftyJSONTests => }/PerformanceTests.swift (100%) rename Tests/{SwiftyJSONTests => }/PrintableTests.swift (100%) rename Tests/{SwiftyJSONTests => }/RawRepresentableTests.swift (100%) rename Tests/{SwiftyJSONTests => }/RawTests.swift (100%) rename Tests/{SwiftyJSONTests => }/SequenceTypeTests.swift (100%) rename Tests/{SwiftyJSONTests => }/StringTests.swift (100%) rename Tests/{SwiftyJSONTests => }/SubscriptTests.swift (100%) rename Tests/{SwiftyJSONTests => Tes}/Tests.json (100%) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 1ec04ff6..be176003 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -114,37 +114,37 @@ /* Begin PBXFileReference section */ 030B6CDC1A6E171D00C2D4F1 /* Info-macOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-macOS.plist"; sourceTree = ""; }; - 1B587CC41DDE04360012D8DB /* MergeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MergeTests.swift; sourceTree = ""; }; + 1B587CC41DDE04360012D8DB /* MergeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MergeTests.swift; path = ../MergeTests.swift; sourceTree = ""; }; 2E4FEFDB19575BE100351305 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 2E4FEFDF19575BE100351305 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; 2E4FEFE019575BE100351305 /* SwiftyJSON.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SwiftyJSON.h; sourceTree = ""; }; 2E4FEFE619575BE100351305 /* SwiftyJSON iOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON iOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; - 5DD502901D9B21810004C112 /* NestedJSONTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NestedJSONTests.swift; sourceTree = ""; }; - 712921EE2004E4EB00DA6340 /* CodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodableTests.swift; sourceTree = ""; }; + 5DD502901D9B21810004C112 /* NestedJSONTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NestedJSONTests.swift; path = ../NestedJSONTests.swift; sourceTree = ""; }; + 712921EE2004E4EB00DA6340 /* CodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = CodableTests.swift; path = ../CodableTests.swift; sourceTree = ""; }; 7236B4F61BAC14150020529B /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 7236B4F71BAC14150020529B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-tvOS.plist"; sourceTree = ""; }; - 9C459EF61A9103B1008C9A41 /* Info-macOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Info-macOS.plist"; sourceTree = ""; }; + 9C459EF61A9103B1008C9A41 /* Info-macOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "Info-macOS.plist"; path = "../Info-macOS.plist"; sourceTree = ""; }; 9C7DFC5B1A9102BD005AA3F7 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 9C7DFC651A9102BD005AA3F7 /* SwiftyJSON macOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON macOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; - A819C49619E1A7DD00ADCC3D /* LiteralConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LiteralConvertibleTests.swift; sourceTree = ""; }; - A819C49819E1B10300ADCC3D /* RawRepresentableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentableTests.swift; sourceTree = ""; }; - A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SubscriptTests.swift; sourceTree = ""; }; - A819C4A019E37FC600ADCC3D /* PrintableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrintableTests.swift; sourceTree = ""; }; - A82A1C0D19D922DC009A653D /* Info-iOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; - A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutabilityTests.swift; sourceTree = ""; }; + A819C49619E1A7DD00ADCC3D /* LiteralConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = LiteralConvertibleTests.swift; path = ../LiteralConvertibleTests.swift; sourceTree = ""; }; + A819C49819E1B10300ADCC3D /* RawRepresentableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RawRepresentableTests.swift; path = ../RawRepresentableTests.swift; sourceTree = ""; }; + A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SubscriptTests.swift; path = ../SubscriptTests.swift; sourceTree = ""; }; + A819C4A019E37FC600ADCC3D /* PrintableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PrintableTests.swift; path = ../PrintableTests.swift; sourceTree = ""; }; + A82A1C0D19D922DC009A653D /* Info-iOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "Info-iOS.plist"; path = "../Info-iOS.plist"; sourceTree = ""; }; + A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MutabilityTests.swift; path = ../MutabilityTests.swift; sourceTree = ""; }; A8491E1D19CD6DAE00CCFAE6 /* SwiftyJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftyJSON.swift; sourceTree = ""; }; A8580F741BCF5C5B00DA927B /* SwiftyJSON tvOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON tvOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; - A8580F781BCF5C5B00DA927B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-tvOS.plist"; sourceTree = ""; }; - A863BE2719EED46F0092A41F /* RawTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawTests.swift; sourceTree = ""; }; - A86BAA0D19EBC32B009EAAEB /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceTests.swift; sourceTree = ""; }; - A87080E319E3C2A600CDE086 /* SequenceTypeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SequenceTypeTests.swift; sourceTree = ""; }; - A87080E519E3DF7800CDE086 /* ComparableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ComparableTests.swift; sourceTree = ""; }; - A87080E719E439DA00CDE086 /* NumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumberTests.swift; sourceTree = ""; }; - A87080E919E43C0700CDE086 /* StringTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StringTests.swift; sourceTree = ""; }; - A885D1D119CF1EE6002FD4C3 /* BaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseTests.swift; sourceTree = ""; }; + A8580F781BCF5C5B00DA927B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = "Info-tvOS.plist"; path = "../Info-tvOS.plist"; sourceTree = ""; }; + A863BE2719EED46F0092A41F /* RawTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RawTests.swift; path = ../RawTests.swift; sourceTree = ""; }; + A86BAA0D19EBC32B009EAAEB /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PerformanceTests.swift; path = ../PerformanceTests.swift; sourceTree = ""; }; + A87080E319E3C2A600CDE086 /* SequenceTypeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SequenceTypeTests.swift; path = ../SequenceTypeTests.swift; sourceTree = ""; }; + A87080E519E3DF7800CDE086 /* ComparableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ComparableTests.swift; path = ../ComparableTests.swift; sourceTree = ""; }; + A87080E719E439DA00CDE086 /* NumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NumberTests.swift; path = ../NumberTests.swift; sourceTree = ""; }; + A87080E919E43C0700CDE086 /* StringTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = StringTests.swift; path = ../StringTests.swift; sourceTree = ""; }; + A885D1D119CF1EE6002FD4C3 /* BaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = BaseTests.swift; path = ../BaseTests.swift; sourceTree = ""; }; A885D1DA19CFCFF0002FD4C3 /* Tests.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = Tests.json; sourceTree = ""; }; - A8B66C8B19E51D6500540692 /* DictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DictionaryTests.swift; sourceTree = ""; }; - A8B66C8D19E52F4200540692 /* ArrayTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ArrayTests.swift; sourceTree = ""; }; + A8B66C8B19E51D6500540692 /* DictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = DictionaryTests.swift; path = ../DictionaryTests.swift; sourceTree = ""; }; + A8B66C8D19E52F4200540692 /* ArrayTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ArrayTests.swift; path = ../ArrayTests.swift; sourceTree = ""; }; E4D7CCE81B9465A700EE7221 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; E4D7CCE91B9465A800EE7221 /* Info-watchOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-watchOS.plist"; sourceTree = ""; }; /* End PBXFileReference section */ @@ -209,7 +209,7 @@ isa = PBXGroup; children = ( 2E4FEFDD19575BE100351305 /* Source */, - 2E4FEFEA19575BE100351305 /* SwiftyJSONTests */, + 2E4FEFEA19575BE100351305 /* Tests */, 2E4FEFDC19575BE100351305 /* Products */, ); sourceTree = ""; @@ -249,11 +249,10 @@ name = "Supporting Files"; sourceTree = ""; }; - 2E4FEFEA19575BE100351305 /* SwiftyJSONTests */ = { + 2E4FEFEA19575BE100351305 /* Tests */ = { isa = PBXGroup; children = ( 1B587CC41DDE04360012D8DB /* MergeTests.swift */, - A885D1DA19CFCFF0002FD4C3 /* Tests.json */, A86BAA0D19EBC32B009EAAEB /* PerformanceTests.swift */, A885D1D119CF1EE6002FD4C3 /* BaseTests.swift */, 5DD502901D9B21810004C112 /* NestedJSONTests.swift */, @@ -272,13 +271,14 @@ 712921EE2004E4EB00DA6340 /* CodableTests.swift */, 2E4FEFEB19575BE100351305 /* Supporting Files */, ); - name = SwiftyJSONTests; - path = Tests/SwiftyJSONTests; + name = Tests; + path = Tests/Tes; sourceTree = ""; }; 2E4FEFEB19575BE100351305 /* Supporting Files */ = { isa = PBXGroup; children = ( + A885D1DA19CFCFF0002FD4C3 /* Tests.json */, A82A1C0D19D922DC009A653D /* Info-iOS.plist */, 9C459EF61A9103B1008C9A41 /* Info-macOS.plist */, A8580F781BCF5C5B00DA927B /* Info-tvOS.plist */, @@ -891,7 +891,7 @@ "DEBUG=1", "$(inherited)", ); - INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-iOS.plist"; + INFOPLIST_FILE = "Tests/Info-iOS.plist"; IPHONEOS_DEPLOYMENT_TARGET = 9.1; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; METAL_ENABLE_DEBUG_INFO = YES; @@ -909,7 +909,7 @@ CODE_SIGN_IDENTITY = ""; DEVELOPMENT_TEAM = ""; GCC_OPTIMIZATION_LEVEL = s; - INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-iOS.plist"; + INFOPLIST_FILE = "Tests/Info-iOS.plist"; IPHONEOS_DEPLOYMENT_TARGET = 9.1; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; METAL_ENABLE_DEBUG_INFO = NO; @@ -1042,7 +1042,7 @@ "DEBUG=1", "$(inherited)", ); - INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-macOS.plist"; + INFOPLIST_FILE = "Tests/Info-macOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = YES; @@ -1062,7 +1062,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; FRAMEWORK_SEARCH_PATHS = ""; GCC_OPTIMIZATION_LEVEL = s; - INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-macOS.plist"; + INFOPLIST_FILE = "Tests/Info-macOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; MTL_ENABLE_DEBUG_INFO = NO; @@ -1096,7 +1096,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; - INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-tvOS.plist"; + INFOPLIST_FILE = "Tests/Info-tvOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.tangplin.SwiftyJSON-tvOS-Tests"; @@ -1116,7 +1116,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = s; - INFOPLIST_FILE = "Tests/SwiftyJSONTests/Info-tvOS.plist"; + INFOPLIST_FILE = "Tests/Info-tvOS.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_BUNDLE_IDENTIFIER = "com.tangplin.SwiftyJSON-tvOS-Tests"; diff --git a/Tests/SwiftyJSONTests/ArrayTests.swift b/Tests/ArrayTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/ArrayTests.swift rename to Tests/ArrayTests.swift diff --git a/Tests/SwiftyJSONTests/BaseTests.swift b/Tests/BaseTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/BaseTests.swift rename to Tests/BaseTests.swift diff --git a/Tests/SwiftyJSONTests/CodableTests.swift b/Tests/CodableTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/CodableTests.swift rename to Tests/CodableTests.swift diff --git a/Tests/SwiftyJSONTests/ComparableTests.swift b/Tests/ComparableTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/ComparableTests.swift rename to Tests/ComparableTests.swift diff --git a/Tests/SwiftyJSONTests/DictionaryTests.swift b/Tests/DictionaryTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/DictionaryTests.swift rename to Tests/DictionaryTests.swift diff --git a/Tests/SwiftyJSONTests/Info-iOS.plist b/Tests/Info-iOS.plist similarity index 100% rename from Tests/SwiftyJSONTests/Info-iOS.plist rename to Tests/Info-iOS.plist diff --git a/Tests/SwiftyJSONTests/Info-macOS.plist b/Tests/Info-macOS.plist similarity index 100% rename from Tests/SwiftyJSONTests/Info-macOS.plist rename to Tests/Info-macOS.plist diff --git a/Tests/SwiftyJSONTests/Info-tvOS.plist b/Tests/Info-tvOS.plist similarity index 100% rename from Tests/SwiftyJSONTests/Info-tvOS.plist rename to Tests/Info-tvOS.plist diff --git a/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift b/Tests/LiteralConvertibleTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/LiteralConvertibleTests.swift rename to Tests/LiteralConvertibleTests.swift diff --git a/Tests/SwiftyJSONTests/MergeTests.swift b/Tests/MergeTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/MergeTests.swift rename to Tests/MergeTests.swift diff --git a/Tests/SwiftyJSONTests/MutabilityTests.swift b/Tests/MutabilityTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/MutabilityTests.swift rename to Tests/MutabilityTests.swift diff --git a/Tests/SwiftyJSONTests/NestedJSONTests.swift b/Tests/NestedJSONTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/NestedJSONTests.swift rename to Tests/NestedJSONTests.swift diff --git a/Tests/SwiftyJSONTests/NumberTests.swift b/Tests/NumberTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/NumberTests.swift rename to Tests/NumberTests.swift diff --git a/Tests/SwiftyJSONTests/PerformanceTests.swift b/Tests/PerformanceTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/PerformanceTests.swift rename to Tests/PerformanceTests.swift diff --git a/Tests/SwiftyJSONTests/PrintableTests.swift b/Tests/PrintableTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/PrintableTests.swift rename to Tests/PrintableTests.swift diff --git a/Tests/SwiftyJSONTests/RawRepresentableTests.swift b/Tests/RawRepresentableTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/RawRepresentableTests.swift rename to Tests/RawRepresentableTests.swift diff --git a/Tests/SwiftyJSONTests/RawTests.swift b/Tests/RawTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/RawTests.swift rename to Tests/RawTests.swift diff --git a/Tests/SwiftyJSONTests/SequenceTypeTests.swift b/Tests/SequenceTypeTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/SequenceTypeTests.swift rename to Tests/SequenceTypeTests.swift diff --git a/Tests/SwiftyJSONTests/StringTests.swift b/Tests/StringTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/StringTests.swift rename to Tests/StringTests.swift diff --git a/Tests/SwiftyJSONTests/SubscriptTests.swift b/Tests/SubscriptTests.swift similarity index 100% rename from Tests/SwiftyJSONTests/SubscriptTests.swift rename to Tests/SubscriptTests.swift diff --git a/Tests/SwiftyJSONTests/Tests.json b/Tests/Tes/Tests.json similarity index 100% rename from Tests/SwiftyJSONTests/Tests.json rename to Tests/Tes/Tests.json From 027f1bc1c0b8c5f7f5fad7a26a6730f7d6458ee8 Mon Sep 17 00:00:00 2001 From: Meghdoot Dhameliya Date: Wed, 26 Sep 2018 12:54:28 +0530 Subject: [PATCH 222/260] SwiftyJSON Model Generator Tools Reference added (#976) SwiftyJSON Model Generator tool reference added --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 32749799..ca69ca6b 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ SwiftyJSON makes it easy to deal with JSON data in Swift. - [Merging](#merging) 5. [Work with Alamofire](#work-with-alamofire) 6. [Work with Moya](#work-with-moya) +7. [SwiftyJSON Model Generator](#swiftyjson-model-generator) > [中文介绍](http://tangplin.github.io/swiftyjson/) @@ -547,3 +548,8 @@ provider.request(.showProducts) { result in } ``` + +## SwiftyJSON Model Generator +Tools to generate SwiftyJSON Models +* [JSON Cafe](http://www.jsoncafe.com/) +* [JSON Export](https://github.com/Ahmed-Ali/JSONExport) From cf762e63d2f4062b755c92d47bb4ef4b76d6edde Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 26 Sep 2018 17:22:43 +0800 Subject: [PATCH 223/260] Remove unused script --- scripts/carthage.sh | 2 -- 1 file changed, 2 deletions(-) delete mode 100755 scripts/carthage.sh diff --git a/scripts/carthage.sh b/scripts/carthage.sh deleted file mode 100755 index aeee56ae..00000000 --- a/scripts/carthage.sh +++ /dev/null @@ -1,2 +0,0 @@ -carthage build --no-skip-current -carthage archive SwiftyJSON From 3f6f1d32df6e5f334593682b20bb829e48bffbee Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 26 Sep 2018 18:03:28 +0800 Subject: [PATCH 224/260] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ca69ca6b..9cf5a68d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,15 @@ # SwiftyJSON -[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0+%20%7C%20macOS%2010.10+%20%7C%20tvOS%209.0+%20%7C%20watchOS%202.0+-333333.svg) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) SwiftyJSON makes it easy to deal with JSON data in Swift. +Platform | Build Status +---------| --------------| +*OS | [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) | +[Linux](https://github.com/IBM-Swift/SwiftyJSON) | [![Build Status](https://travis-ci.org/IBM-Swift/SwiftyJSON.svg?branch=master)](https://travis-ci.org/IBM-Swift/SwiftyJSON) | + + 1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) 2. [Requirements](#requirements) 3. [Integration](#integration) From 53559ee35727703bfef031af74babf07ead15f7d Mon Sep 17 00:00:00 2001 From: Happy HumanPointer <45888860+SafelySwift@users.noreply.github.com> Date: Sun, 31 Mar 2019 08:15:21 -0400 Subject: [PATCH 225/260] Update README.md (#1010) * Update README.md * Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9cf5a68d..0aedb469 100644 --- a/README.md +++ b/README.md @@ -73,11 +73,12 @@ And don't worry about the Optional Wrapping thing. It's done for you automatical ```swift let json = JSON(data: dataFromNetworking) -if let userName = json[999999]["wrong_key"]["wrong_name"].string { +let result = json[999999]["wrong_key"]["wrong_name"] +if let userName = result.string { //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety } else { //Print the error - print(json[999999]["wrong_key"]["wrong_name"]) + print(result.error) } ``` @@ -168,7 +169,7 @@ let name = json[0].double ```swift // Getting an array of string from a JSON Array -let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue}) +let arrayNames = json["users"].arrayValue.map {$0["name"].stringValue} ``` ```swift From 645f1e39bd53dd07fb2a1b7cc8d8be043b701bcc Mon Sep 17 00:00:00 2001 From: Scott Albertson Date: Sun, 31 Mar 2019 10:39:11 -0700 Subject: [PATCH 226/260] Add a "Reviewed by Hound" badge (#1006) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0aedb469..7a10e29c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # SwiftyJSON -[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com) SwiftyJSON makes it easy to deal with JSON data in Swift. From 8bbb74eec7366de10f78a05fc9dff588337c117e Mon Sep 17 00:00:00 2001 From: Moritz Vetter Date: Sun, 31 Mar 2019 19:44:03 +0200 Subject: [PATCH 227/260] Updated swift-tools to version 5.0 (#1013) * Updated SwiftyJSON to swift-tools 5.0 * supply path to Tests.json in a different manner * Made changes comply with xcode building scheme, removed compliance with [1/3] Compiling Swift Module 'SwiftyJSON' (1 sources) [2/3] Compiling Swift Module 'SwiftJSONTests' (17 sources) [3/3] Linking ./.build/x86_64-apple-macosx/debug/SwiftyJSONPackageTests.xctest/Contents/MacOS/SwiftyJSONPackageTests Exited with signal code 4 --- Package.swift | 12 +++++- Source/{ => SwiftyJSON}/SwiftyJSON.h | 0 Source/{ => SwiftyJSON}/SwiftyJSON.swift | 0 SwiftyJSON.xcodeproj/project.pbxproj | 39 ++++++++++--------- .../xcshareddata/IDEWorkspaceChecks.plist | 8 ++++ Tests/{ => SwiftJSONTests}/ArrayTests.swift | 0 Tests/{ => SwiftJSONTests}/BaseTests.swift | 2 + Tests/{ => SwiftJSONTests}/CodableTests.swift | 0 .../ComparableTests.swift | 0 .../DictionaryTests.swift | 0 .../LiteralConvertibleTests.swift | 0 Tests/{ => SwiftJSONTests}/MergeTests.swift | 0 .../MutabilityTests.swift | 0 .../NestedJSONTests.swift | 0 Tests/{ => SwiftJSONTests}/NumberTests.swift | 0 .../PerformanceTests.swift | 0 .../{ => SwiftJSONTests}/PrintableTests.swift | 0 .../RawRepresentableTests.swift | 0 Tests/{ => SwiftJSONTests}/RawTests.swift | 0 .../SequenceTypeTests.swift | 0 Tests/{ => SwiftJSONTests}/StringTests.swift | 0 .../{ => SwiftJSONTests}/SubscriptTests.swift | 0 22 files changed, 41 insertions(+), 20 deletions(-) rename Source/{ => SwiftyJSON}/SwiftyJSON.h (100%) rename Source/{ => SwiftyJSON}/SwiftyJSON.swift (100%) create mode 100644 SwiftyJSON.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist rename Tests/{ => SwiftJSONTests}/ArrayTests.swift (100%) rename Tests/{ => SwiftJSONTests}/BaseTests.swift (99%) rename Tests/{ => SwiftJSONTests}/CodableTests.swift (100%) rename Tests/{ => SwiftJSONTests}/ComparableTests.swift (100%) rename Tests/{ => SwiftJSONTests}/DictionaryTests.swift (100%) rename Tests/{ => SwiftJSONTests}/LiteralConvertibleTests.swift (100%) rename Tests/{ => SwiftJSONTests}/MergeTests.swift (100%) rename Tests/{ => SwiftJSONTests}/MutabilityTests.swift (100%) rename Tests/{ => SwiftJSONTests}/NestedJSONTests.swift (100%) rename Tests/{ => SwiftJSONTests}/NumberTests.swift (100%) rename Tests/{ => SwiftJSONTests}/PerformanceTests.swift (100%) rename Tests/{ => SwiftJSONTests}/PrintableTests.swift (100%) rename Tests/{ => SwiftJSONTests}/RawRepresentableTests.swift (100%) rename Tests/{ => SwiftJSONTests}/RawTests.swift (100%) rename Tests/{ => SwiftJSONTests}/SequenceTypeTests.swift (100%) rename Tests/{ => SwiftJSONTests}/StringTests.swift (100%) rename Tests/{ => SwiftJSONTests}/SubscriptTests.swift (100%) diff --git a/Package.swift b/Package.swift index 801f1d5d..d9792b91 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,14 @@ +// swift-tools-version:5.0 import PackageDescription let package = Package( - name: "SwiftyJSON") + name: "SwiftyJSON", + products: [ + .library(name: "SwiftyJSON", targets: ["SwiftyJSON"]), + ], + dependencies: [], + targets: [ + .target(name: "SwiftyJSON", dependencies: []), + .testTarget(name: "SwiftJSONTests", dependencies: ["SwiftyJSON"]), + ] +) diff --git a/Source/SwiftyJSON.h b/Source/SwiftyJSON/SwiftyJSON.h similarity index 100% rename from Source/SwiftyJSON.h rename to Source/SwiftyJSON/SwiftyJSON.h diff --git a/Source/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift similarity index 100% rename from Source/SwiftyJSON.swift rename to Source/SwiftyJSON/SwiftyJSON.swift diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index be176003..7b08ff75 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -114,37 +114,37 @@ /* Begin PBXFileReference section */ 030B6CDC1A6E171D00C2D4F1 /* Info-macOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-macOS.plist"; sourceTree = ""; }; - 1B587CC41DDE04360012D8DB /* MergeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MergeTests.swift; path = ../MergeTests.swift; sourceTree = ""; }; + 1B587CC41DDE04360012D8DB /* MergeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MergeTests.swift; path = ../SwiftJSONTests/MergeTests.swift; sourceTree = ""; }; 2E4FEFDB19575BE100351305 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 2E4FEFDF19575BE100351305 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; - 2E4FEFE019575BE100351305 /* SwiftyJSON.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SwiftyJSON.h; sourceTree = ""; }; + 2E4FEFE019575BE100351305 /* SwiftyJSON.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SwiftyJSON.h; path = SwiftyJSON/SwiftyJSON.h; sourceTree = ""; }; 2E4FEFE619575BE100351305 /* SwiftyJSON iOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON iOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; - 5DD502901D9B21810004C112 /* NestedJSONTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NestedJSONTests.swift; path = ../NestedJSONTests.swift; sourceTree = ""; }; - 712921EE2004E4EB00DA6340 /* CodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = CodableTests.swift; path = ../CodableTests.swift; sourceTree = ""; }; + 5DD502901D9B21810004C112 /* NestedJSONTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NestedJSONTests.swift; path = ../SwiftJSONTests/NestedJSONTests.swift; sourceTree = ""; }; + 712921EE2004E4EB00DA6340 /* CodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = CodableTests.swift; path = ../SwiftJSONTests/CodableTests.swift; sourceTree = ""; }; 7236B4F61BAC14150020529B /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 7236B4F71BAC14150020529B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-tvOS.plist"; sourceTree = ""; }; 9C459EF61A9103B1008C9A41 /* Info-macOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "Info-macOS.plist"; path = "../Info-macOS.plist"; sourceTree = ""; }; 9C7DFC5B1A9102BD005AA3F7 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 9C7DFC651A9102BD005AA3F7 /* SwiftyJSON macOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON macOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; - A819C49619E1A7DD00ADCC3D /* LiteralConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = LiteralConvertibleTests.swift; path = ../LiteralConvertibleTests.swift; sourceTree = ""; }; - A819C49819E1B10300ADCC3D /* RawRepresentableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RawRepresentableTests.swift; path = ../RawRepresentableTests.swift; sourceTree = ""; }; - A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SubscriptTests.swift; path = ../SubscriptTests.swift; sourceTree = ""; }; - A819C4A019E37FC600ADCC3D /* PrintableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PrintableTests.swift; path = ../PrintableTests.swift; sourceTree = ""; }; + A819C49619E1A7DD00ADCC3D /* LiteralConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = LiteralConvertibleTests.swift; path = ../SwiftJSONTests/LiteralConvertibleTests.swift; sourceTree = ""; }; + A819C49819E1B10300ADCC3D /* RawRepresentableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RawRepresentableTests.swift; path = ../SwiftJSONTests/RawRepresentableTests.swift; sourceTree = ""; }; + A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SubscriptTests.swift; path = ../SwiftJSONTests/SubscriptTests.swift; sourceTree = ""; }; + A819C4A019E37FC600ADCC3D /* PrintableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PrintableTests.swift; path = ../SwiftJSONTests/PrintableTests.swift; sourceTree = ""; }; A82A1C0D19D922DC009A653D /* Info-iOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "Info-iOS.plist"; path = "../Info-iOS.plist"; sourceTree = ""; }; - A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MutabilityTests.swift; path = ../MutabilityTests.swift; sourceTree = ""; }; - A8491E1D19CD6DAE00CCFAE6 /* SwiftyJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftyJSON.swift; sourceTree = ""; }; + A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MutabilityTests.swift; path = ../SwiftJSONTests/MutabilityTests.swift; sourceTree = ""; }; + A8491E1D19CD6DAE00CCFAE6 /* SwiftyJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SwiftyJSON.swift; path = SwiftyJSON/SwiftyJSON.swift; sourceTree = ""; }; A8580F741BCF5C5B00DA927B /* SwiftyJSON tvOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON tvOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; A8580F781BCF5C5B00DA927B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = "Info-tvOS.plist"; path = "../Info-tvOS.plist"; sourceTree = ""; }; - A863BE2719EED46F0092A41F /* RawTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RawTests.swift; path = ../RawTests.swift; sourceTree = ""; }; - A86BAA0D19EBC32B009EAAEB /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PerformanceTests.swift; path = ../PerformanceTests.swift; sourceTree = ""; }; - A87080E319E3C2A600CDE086 /* SequenceTypeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SequenceTypeTests.swift; path = ../SequenceTypeTests.swift; sourceTree = ""; }; - A87080E519E3DF7800CDE086 /* ComparableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ComparableTests.swift; path = ../ComparableTests.swift; sourceTree = ""; }; - A87080E719E439DA00CDE086 /* NumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NumberTests.swift; path = ../NumberTests.swift; sourceTree = ""; }; - A87080E919E43C0700CDE086 /* StringTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = StringTests.swift; path = ../StringTests.swift; sourceTree = ""; }; - A885D1D119CF1EE6002FD4C3 /* BaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = BaseTests.swift; path = ../BaseTests.swift; sourceTree = ""; }; + A863BE2719EED46F0092A41F /* RawTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RawTests.swift; path = ../SwiftJSONTests/RawTests.swift; sourceTree = ""; }; + A86BAA0D19EBC32B009EAAEB /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PerformanceTests.swift; path = ../SwiftJSONTests/PerformanceTests.swift; sourceTree = ""; }; + A87080E319E3C2A600CDE086 /* SequenceTypeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SequenceTypeTests.swift; path = ../SwiftJSONTests/SequenceTypeTests.swift; sourceTree = ""; }; + A87080E519E3DF7800CDE086 /* ComparableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ComparableTests.swift; path = ../SwiftJSONTests/ComparableTests.swift; sourceTree = ""; }; + A87080E719E439DA00CDE086 /* NumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NumberTests.swift; path = ../SwiftJSONTests/NumberTests.swift; sourceTree = ""; }; + A87080E919E43C0700CDE086 /* StringTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = StringTests.swift; path = ../SwiftJSONTests/StringTests.swift; sourceTree = ""; }; + A885D1D119CF1EE6002FD4C3 /* BaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = BaseTests.swift; path = ../SwiftJSONTests/BaseTests.swift; sourceTree = ""; }; A885D1DA19CFCFF0002FD4C3 /* Tests.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = Tests.json; sourceTree = ""; }; - A8B66C8B19E51D6500540692 /* DictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = DictionaryTests.swift; path = ../DictionaryTests.swift; sourceTree = ""; }; - A8B66C8D19E52F4200540692 /* ArrayTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ArrayTests.swift; path = ../ArrayTests.swift; sourceTree = ""; }; + A8B66C8B19E51D6500540692 /* DictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = DictionaryTests.swift; path = ../SwiftJSONTests/DictionaryTests.swift; sourceTree = ""; }; + A8B66C8D19E52F4200540692 /* ArrayTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ArrayTests.swift; path = ../SwiftJSONTests/ArrayTests.swift; sourceTree = ""; }; E4D7CCE81B9465A700EE7221 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; E4D7CCE91B9465A800EE7221 /* Info-watchOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-watchOS.plist"; sourceTree = ""; }; /* End PBXFileReference section */ @@ -502,6 +502,7 @@ developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( + English, en, ); mainGroup = 2E4FEFD119575BE100351305; diff --git a/SwiftyJSON.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/SwiftyJSON.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/SwiftyJSON.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Tests/ArrayTests.swift b/Tests/SwiftJSONTests/ArrayTests.swift similarity index 100% rename from Tests/ArrayTests.swift rename to Tests/SwiftJSONTests/ArrayTests.swift diff --git a/Tests/BaseTests.swift b/Tests/SwiftJSONTests/BaseTests.swift similarity index 99% rename from Tests/BaseTests.swift rename to Tests/SwiftJSONTests/BaseTests.swift index 16dab02c..9139c204 100644 --- a/Tests/BaseTests.swift +++ b/Tests/SwiftJSONTests/BaseTests.swift @@ -31,6 +31,8 @@ class BaseTests: XCTestCase { super.setUp() +// let file = "./Tests/Tes/Tests.json" +// self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) if let file = Bundle(for: BaseTests.self).path(forResource: "Tests", ofType: "json") { self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { diff --git a/Tests/CodableTests.swift b/Tests/SwiftJSONTests/CodableTests.swift similarity index 100% rename from Tests/CodableTests.swift rename to Tests/SwiftJSONTests/CodableTests.swift diff --git a/Tests/ComparableTests.swift b/Tests/SwiftJSONTests/ComparableTests.swift similarity index 100% rename from Tests/ComparableTests.swift rename to Tests/SwiftJSONTests/ComparableTests.swift diff --git a/Tests/DictionaryTests.swift b/Tests/SwiftJSONTests/DictionaryTests.swift similarity index 100% rename from Tests/DictionaryTests.swift rename to Tests/SwiftJSONTests/DictionaryTests.swift diff --git a/Tests/LiteralConvertibleTests.swift b/Tests/SwiftJSONTests/LiteralConvertibleTests.swift similarity index 100% rename from Tests/LiteralConvertibleTests.swift rename to Tests/SwiftJSONTests/LiteralConvertibleTests.swift diff --git a/Tests/MergeTests.swift b/Tests/SwiftJSONTests/MergeTests.swift similarity index 100% rename from Tests/MergeTests.swift rename to Tests/SwiftJSONTests/MergeTests.swift diff --git a/Tests/MutabilityTests.swift b/Tests/SwiftJSONTests/MutabilityTests.swift similarity index 100% rename from Tests/MutabilityTests.swift rename to Tests/SwiftJSONTests/MutabilityTests.swift diff --git a/Tests/NestedJSONTests.swift b/Tests/SwiftJSONTests/NestedJSONTests.swift similarity index 100% rename from Tests/NestedJSONTests.swift rename to Tests/SwiftJSONTests/NestedJSONTests.swift diff --git a/Tests/NumberTests.swift b/Tests/SwiftJSONTests/NumberTests.swift similarity index 100% rename from Tests/NumberTests.swift rename to Tests/SwiftJSONTests/NumberTests.swift diff --git a/Tests/PerformanceTests.swift b/Tests/SwiftJSONTests/PerformanceTests.swift similarity index 100% rename from Tests/PerformanceTests.swift rename to Tests/SwiftJSONTests/PerformanceTests.swift diff --git a/Tests/PrintableTests.swift b/Tests/SwiftJSONTests/PrintableTests.swift similarity index 100% rename from Tests/PrintableTests.swift rename to Tests/SwiftJSONTests/PrintableTests.swift diff --git a/Tests/RawRepresentableTests.swift b/Tests/SwiftJSONTests/RawRepresentableTests.swift similarity index 100% rename from Tests/RawRepresentableTests.swift rename to Tests/SwiftJSONTests/RawRepresentableTests.swift diff --git a/Tests/RawTests.swift b/Tests/SwiftJSONTests/RawTests.swift similarity index 100% rename from Tests/RawTests.swift rename to Tests/SwiftJSONTests/RawTests.swift diff --git a/Tests/SequenceTypeTests.swift b/Tests/SwiftJSONTests/SequenceTypeTests.swift similarity index 100% rename from Tests/SequenceTypeTests.swift rename to Tests/SwiftJSONTests/SequenceTypeTests.swift diff --git a/Tests/StringTests.swift b/Tests/SwiftJSONTests/StringTests.swift similarity index 100% rename from Tests/StringTests.swift rename to Tests/SwiftJSONTests/StringTests.swift diff --git a/Tests/SubscriptTests.swift b/Tests/SwiftJSONTests/SubscriptTests.swift similarity index 100% rename from Tests/SubscriptTests.swift rename to Tests/SwiftJSONTests/SubscriptTests.swift From f7ec2badf80fd27ab5f2bd15599530bed41717e7 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 2 Apr 2019 15:08:09 +0800 Subject: [PATCH 228/260] Bump pod version to 4.3.0 and update ci image to Xcode 10.2 --- .travis.yml | 2 +- SwiftyJSON.podspec | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 34acdea7..17140ab1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: objective-c -osx_image: xcode10 +osx_image: xcode10.2 xcode_sdk: iphonesimulator12.0 script: - set -o pipefail diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index d5fbc3d1..d486f0a1 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,13 +1,13 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "4.2.0" + s.version = "4.3.0" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } s.authors = { "lingoer" => "lingoerer@gmail.com", "tangplin" => "tangplin@gmail.com" } s.requires_arc = true - s.swift_version = "4.2" + s.swift_version = "5.0" s.osx.deployment_target = "10.9" s.ios.deployment_target = "8.0" s.watchos.deployment_target = "3.0" From e0511293fcdc0a31f585370be8623e745ec34403 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Tue, 2 Apr 2019 15:54:01 +0800 Subject: [PATCH 229/260] Update project settings --- Example/Example.xcodeproj/project.pbxproj | 12 +++---- Example/Example/AppDelegate.swift | 2 +- SwiftyJSON.xcodeproj/project.pbxproj | 36 ++++++++++--------- .../xcschemes/SwiftyJSON iOS.xcscheme | 2 +- .../xcschemes/SwiftyJSON macOS.xcscheme | 2 +- .../xcschemes/SwiftyJSON tvOS.xcscheme | 2 +- .../xcschemes/SwiftyJSON watchOS.xcscheme | 2 +- 7 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index 54e81356..a58da571 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -124,19 +124,19 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0700; - LastUpgradeCheck = 0930; + LastUpgradeCheck = 1020; ORGANIZATIONNAME = swiftyjson; TargetAttributes = { A82A1C1819D926B8009A653D = { CreatedOnToolsVersion = 6.0.1; - LastSwiftMigration = 0930; + LastSwiftMigration = 1020; ProvisioningStyle = Manual; }; }; }; buildConfigurationList = A82A1C1419D926B8009A653D /* Build configuration list for PBXProject "Example" */; compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, @@ -313,8 +313,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_SWIFT3_OBJC_INFERENCE = Default; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 5.0; }; name = Debug; }; @@ -329,8 +328,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_SWIFT3_OBJC_INFERENCE = Default; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 5.0; }; name = Release; }; diff --git a/Example/Example/AppDelegate.swift b/Example/Example/AppDelegate.swift index e2af9aa6..c4236b1d 100644 --- a/Example/Example/AppDelegate.swift +++ b/Example/Example/AppDelegate.swift @@ -28,7 +28,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let navigationController = self.window?.rootViewController as! UINavigationController let viewController = navigationController.topViewController as! ViewController diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 7b08ff75..8160930b 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -457,7 +457,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0710; - LastUpgradeCheck = 0930; + LastUpgradeCheck = 1020; TargetAttributes = { 2E4FEFDA19575BE100351305 = { CreatedOnToolsVersion = 6.0; @@ -499,11 +499,11 @@ }; buildConfigurationList = 2E4FEFD519575BE100351305 /* Build configuration list for PBXProject "SwiftyJSON" */; compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( - English, en, + Base, ); mainGroup = 2E4FEFD119575BE100351305; productRefGroup = 2E4FEFDC19575BE100351305 /* Products */; @@ -723,6 +723,7 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -783,6 +784,7 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -854,7 +856,7 @@ SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_SWIFT3_OBJC_INFERENCE = Default; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 5.0; }; name = Debug; }; @@ -878,7 +880,7 @@ PRODUCT_NAME = SwiftyJSON; SKIP_INSTALL = YES; SWIFT_SWIFT3_OBJC_INFERENCE = Default; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 5.0; }; name = Release; }; @@ -900,7 +902,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_SWIFT3_OBJC_INFERENCE = Default; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 5.0; }; name = Debug; }; @@ -917,7 +919,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_SWIFT3_OBJC_INFERENCE = Default; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 5.0; }; name = Release; }; @@ -942,7 +944,7 @@ SDKROOT = appletvos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = 3; TVOS_DEPLOYMENT_TARGET = 9.0; }; @@ -968,7 +970,7 @@ PRODUCT_NAME = SwiftyJSON; SDKROOT = appletvos; SKIP_INSTALL = YES; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = 3; TVOS_DEPLOYMENT_TARGET = 9.0; }; @@ -1001,7 +1003,7 @@ SDKROOT = macosx; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; }; name = Debug; }; @@ -1028,7 +1030,7 @@ PRODUCT_NAME = "$(PROJECT_NAME)"; SDKROOT = macosx; SKIP_INSTALL = YES; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; }; name = Release; }; @@ -1051,7 +1053,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; }; name = Debug; }; @@ -1070,7 +1072,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; }; name = Release; }; @@ -1104,7 +1106,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; TVOS_DEPLOYMENT_TARGET = 9.0; }; name = Debug; @@ -1123,7 +1125,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "com.tangplin.SwiftyJSON-tvOS-Tests"; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; TVOS_DEPLOYMENT_TARGET = 9.0; }; name = Release; @@ -1150,7 +1152,7 @@ SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = 4; WATCHOS_DEPLOYMENT_TARGET = 3.0; }; @@ -1177,7 +1179,7 @@ SDKROOT = watchos; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = "watchsimulator watchos"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = 4; WATCHOS_DEPLOYMENT_TARGET = 3.0; }; diff --git a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON iOS.xcscheme b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON iOS.xcscheme index 98076542..f4d10cb9 100644 --- a/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON iOS.xcscheme +++ b/SwiftyJSON.xcodeproj/xcshareddata/xcschemes/SwiftyJSON iOS.xcscheme @@ -1,6 +1,6 @@ Date: Tue, 2 Apr 2019 18:39:43 +0800 Subject: [PATCH 230/260] chore: improve code base --- Example/Example.xcodeproj/project.pbxproj | 2 +- Example/Playground.playground/Contents.swift | 1 - Package.swift | 11 +- Source/SwiftyJSON/SwiftyJSON.swift | 575 ++++++++----------- SwiftyJSON.podspec | 2 +- 5 files changed, 234 insertions(+), 357 deletions(-) diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj index a58da571..e0a5e55e 100644 --- a/Example/Example.xcodeproj/project.pbxproj +++ b/Example/Example.xcodeproj/project.pbxproj @@ -32,7 +32,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 04294C501BE5A9DE00D0397E /* Playground.playground */ = {isa = PBXFileReference; lastKnownFileType = file.playground; path = Playground.playground; sourceTree = ""; }; + 04294C501BE5A9DE00D0397E /* Playground.playground */ = {isa = PBXFileReference; lastKnownFileType = file.playground; path = Playground.playground; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 04733F511D92E6ED002E3A99 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A82A1C1919D926B8009A653D /* Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Example.app; sourceTree = BUILT_PRODUCTS_DIR; }; A82A1C1D19D926B8009A653D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; diff --git a/Example/Playground.playground/Contents.swift b/Example/Playground.playground/Contents.swift index 9306d850..7542d181 100644 --- a/Example/Playground.playground/Contents.swift +++ b/Example/Playground.playground/Contents.swift @@ -29,7 +29,6 @@ let jsonString = String(data: jsonData!, encoding: .utf8) ### Initialization */ -import SwiftyJSON let json1 = try? JSON(data: jsonData!) /*: diff --git a/Package.swift b/Package.swift index d9792b91..1a60e2e7 100644 --- a/Package.swift +++ b/Package.swift @@ -3,12 +3,15 @@ import PackageDescription let package = Package( name: "SwiftyJSON", + platforms: [ + .macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v3) + ], products: [ - .library(name: "SwiftyJSON", targets: ["SwiftyJSON"]), + .library(name: "SwiftyJSON", targets: ["SwiftyJSON"]) ], - dependencies: [], targets: [ .target(name: "SwiftyJSON", dependencies: []), - .testTarget(name: "SwiftJSONTests", dependencies: ["SwiftyJSON"]), - ] + .testTarget(name: "SwiftJSONTests", dependencies: ["SwiftyJSON"]) + ], + swiftLanguageVersions: [.v5] ) diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index a6c1f3a6..f7a3f085 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -138,7 +138,7 @@ public struct JSON { - returns: The created JSON */ fileprivate init(jsonObject: Any) { - self.object = jsonObject + object = jsonObject } /** @@ -174,14 +174,14 @@ public struct JSON { Typecheck is set to true for the first recursion level to prevent total override of the source JSON */ fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { - if self.type == other.type { - switch self.type { + if type == other.type { + switch type { case .dictionary: for (key, _) in other { try self[key].merge(with: other[key], typecheck: false) } case .array: - self = JSON(self.arrayValue + other.arrayValue) + self = JSON(arrayValue + other.arrayValue) default: self = other } @@ -211,19 +211,13 @@ public struct JSON { /// Object in JSON public var object: Any { get { - switch self.type { - case .array: - return self.rawArray - case .dictionary: - return self.rawDictionary - case .string: - return self.rawString - case .number: - return self.rawNumber - case .bool: - return self.rawBool - default: - return self.rawNull + switch type { + case .array: return rawArray + case .dictionary: return rawDictionary + case .string: return rawString + case .number: return rawNumber + case .bool: return rawBool + default: return rawNull } } set { @@ -232,24 +226,24 @@ public struct JSON { case let number as NSNumber: if number.isBool { type = .bool - self.rawBool = number.boolValue + rawBool = number.boolValue } else { type = .number - self.rawNumber = number + rawNumber = number } case let string as String: type = .string - self.rawString = string + rawString = string case _ as NSNull: type = .null case nil: type = .null case let array as [Any]: type = .array - self.rawArray = array + rawArray = array case let dictionary as [String: Any]: type = .dictionary - self.rawDictionary = dictionary + rawDictionary = dictionary default: type = .unknown error = SwiftyJSONError.unsupportedType @@ -271,11 +265,11 @@ private func unwrap(_ object: Any) -> Any { case let array as [Any]: return array.map(unwrap) case let dictionary as [String: Any]: - var unwrappedDic = dictionary - for (k, v) in dictionary { - unwrappedDic[k] = unwrap(v) + var d = dictionary + dictionary.forEach { pair in + d[pair.key] = unwrap(pair.value) } - return unwrappedDic + return d default: return object } @@ -288,24 +282,18 @@ public enum Index: Comparable { static public func == (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { - case (.array(let left), .array(let right)): - return left == right - case (.dictionary(let left), .dictionary(let right)): - return left == right - case (.null, .null): return true - default: - return false + case (.array(let left), .array(let right)): return left == right + case (.dictionary(let left), .dictionary(let right)): return left == right + case (.null, .null): return true + default: return false } } static public func < (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { - case (.array(let left), .array(let right)): - return left < right - case (.dictionary(let left), .dictionary(let right)): - return left < right - default: - return false + case (.array(let left), .array(let right)): return left < right + case (.dictionary(let left), .dictionary(let right)): return left < right + default: return false } } } @@ -319,46 +307,33 @@ extension JSON: Swift.Collection { public var startIndex: Index { switch type { - case .array: - return .array(rawArray.startIndex) - case .dictionary: - return .dictionary(rawDictionary.startIndex) - default: - return .null + case .array: return .array(rawArray.startIndex) + case .dictionary: return .dictionary(rawDictionary.startIndex) + default: return .null } } public var endIndex: Index { switch type { - case .array: - return .array(rawArray.endIndex) - case .dictionary: - return .dictionary(rawDictionary.endIndex) - default: - return .null + case .array: return .array(rawArray.endIndex) + case .dictionary: return .dictionary(rawDictionary.endIndex) + default: return .null } } public func index(after i: Index) -> Index { switch i { - case .array(let idx): - return .array(rawArray.index(after: idx)) - case .dictionary(let idx): - return .dictionary(rawDictionary.index(after: idx)) - default: - return .null + case .array(let idx): return .array(rawArray.index(after: idx)) + case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) + default: return .null } } public subscript (position: Index) -> (String, JSON) { switch position { - case .array(let idx): - return (String(idx), JSON(self.rawArray[idx])) - case .dictionary(let idx): - let (key, value) = self.rawDictionary[idx] - return (key, JSON(value)) - default: - return ("", JSON.null) + case .array(let idx): return (String(idx), JSON(rawArray[idx])) + case .dictionary(let idx): return (rawDictionary[idx].key, JSON(rawDictionary[idx].value)) + default: return ("", JSON.null) } } } @@ -394,12 +369,12 @@ extension JSON { /// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { - if self.type != .array { + if type != .array { var r = JSON.null r.error = self.error ?? SwiftyJSONError.wrongType return r - } else if self.rawArray.indices.contains(index) { - return JSON(self.rawArray[index]) + } else if rawArray.indices.contains(index) { + return JSON(rawArray[index]) } else { var r = JSON.null r.error = SwiftyJSONError.indexOutOfBounds @@ -407,10 +382,10 @@ extension JSON { } } set { - if self.type == .array && - self.rawArray.indices.contains(index) && + if type == .array && + rawArray.indices.contains(index) && newValue.error == nil { - self.rawArray[index] = newValue.object + rawArray[index] = newValue.object } } } @@ -419,8 +394,8 @@ extension JSON { fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null - if self.type == .dictionary { - if let o = self.rawDictionary[key] { + if type == .dictionary { + if let o = rawDictionary[key] { r = JSON(o) } else { r.error = SwiftyJSONError.notExist @@ -431,8 +406,8 @@ extension JSON { return r } set { - if self.type == .dictionary && newValue.error == nil { - self.rawDictionary[key] = newValue.object + if type == .dictionary && newValue.error == nil { + rawDictionary[key] = newValue.object } } } @@ -442,13 +417,13 @@ extension JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] - case .key(let key): return self[key: key] + case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue - case .key(let key): self[key: key] = newValue + case .key(let key): self[key: key] = newValue } } } @@ -476,10 +451,8 @@ extension JSON { } set { switch path.count { - case 0: - return - case 1: - self[sub:path[0]].object = newValue.object + case 0: return + case 1: self[sub:path[0]].object = newValue.object default: var aPath = path aPath.remove(at: 0) @@ -576,15 +549,15 @@ extension JSON: Swift.RawRepresentable { } public var rawValue: Any { - return self.object + return object } public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { - guard JSONSerialization.isValidJSONObject(self.object) else { + guard JSONSerialization.isValidJSONObject(object) else { throw SwiftyJSONError.invalidJSON } - return try JSONSerialization.data(withJSONObject: self.object, options: opt) + return try JSONSerialization.data(withJSONObject: object, options: opt) } public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { @@ -609,16 +582,16 @@ extension JSON: Swift.RawRepresentable { fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON } - switch self.type { + switch type { case .dictionary: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted - let data = try self.rawData(options: jsonOption) + let data = try rawData(options: jsonOption) return String(data: data, encoding: encoding) } - guard let dict = self.object as? [String: Any?] else { + guard let dict = object as? [String: Any?] else { return nil } let body = try dict.keys.map { key throws -> String in @@ -648,11 +621,11 @@ extension JSON: Swift.RawRepresentable { do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted - let data = try self.rawData(options: jsonOption) + let data = try rawData(options: jsonOption) return String(data: data, encoding: encoding) } - guard let array = self.object as? [Any?] else { + guard let array = object as? [Any?] else { return nil } let body = try array.map { value throws -> String in @@ -675,16 +648,11 @@ extension JSON: Swift.RawRepresentable { } catch _ { return nil } - case .string: - return self.rawString - case .number: - return self.rawNumber.stringValue - case .bool: - return self.rawBool.description - case .null: - return "null" - default: - return nil + case .string: return rawString + case .number: return rawNumber.stringValue + case .bool: return rawBool.description + case .null: return "null" + default: return nil } } } @@ -694,11 +662,7 @@ extension JSON: Swift.RawRepresentable { extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { - if let string = self.rawString(options: .prettyPrinted) { - return string - } else { - return "unknown" - } + return rawString(options: .prettyPrinted) ?? "unknown" } public var debugDescription: String { @@ -712,11 +676,7 @@ extension JSON { //Optional [JSON] public var array: [JSON]? { - if self.type == .array { - return self.rawArray.map { JSON($0) } - } else { - return nil - } + return type == .array ? rawArray.map { JSON($0) } : nil } //Non-optional [JSON] @@ -727,19 +687,13 @@ extension JSON { //Optional [Any] public var arrayObject: [Any]? { get { - switch self.type { - case .array: - return self.rawArray - default: - return nil + switch type { + case .array: return rawArray + default: return nil } } set { - if let array = newValue { - self.object = array - } else { - self.object = NSNull() - } + self.object = newValue ?? NSNull() } } } @@ -750,10 +704,10 @@ extension JSON { //Optional [String : JSON] public var dictionary: [String: JSON]? { - if self.type == .dictionary { + if type == .dictionary { var d = [String: JSON](minimumCapacity: rawDictionary.count) - for (key, value) in rawDictionary { - d[key] = JSON(value) + rawDictionary.forEach { pair in + d[pair.key] = JSON(pair.value) } return d } else { @@ -763,26 +717,20 @@ extension JSON { //Non-optional [String : JSON] public var dictionaryValue: [String: JSON] { - return self.dictionary ?? [:] + return dictionary ?? [:] } //Optional [String : Any] public var dictionaryObject: [String: Any]? { get { - switch self.type { - case .dictionary: - return self.rawDictionary - default: - return nil + switch type { + case .dictionary: return rawDictionary + default: return nil } } set { - if let v = newValue { - self.object = v - } else { - self.object = NSNull() - } + object = newValue ?? NSNull() } } } @@ -794,38 +742,28 @@ extension JSON { // : Swift.Bool //Optional bool public var bool: Bool? { get { - switch self.type { - case .bool: - return self.rawBool - default: - return nil + switch type { + case .bool: return rawBool + default: return nil } } set { - if let newValue = newValue { - self.object = newValue as Bool - } else { - self.object = NSNull() - } + object = newValue ?? NSNull() } } //Non-optional bool public var boolValue: Bool { get { - switch self.type { - case .bool: - return self.rawBool - case .number: - return self.rawNumber.boolValue - case .string: - return ["true", "y", "t", "yes", "1"].contains { self.rawString.caseInsensitiveCompare($0) == .orderedSame } - default: - return false + switch type { + case .bool: return rawBool + case .number: return rawNumber.boolValue + case .string: return ["true", "y", "t", "yes", "1"].contains { rawString.caseInsensitiveCompare($0) == .orderedSame } + default: return false } } set { - self.object = newValue + object = newValue } } } @@ -837,38 +775,28 @@ extension JSON { //Optional string public var string: String? { get { - switch self.type { - case .string: - return self.object as? String - default: - return nil + switch type { + case .string: return object as? String + default: return nil } } set { - if let newValue = newValue { - self.object = NSString(string: newValue) - } else { - self.object = NSNull() - } + object = newValue ?? NSNull() } } //Non-optional string public var stringValue: String { get { - switch self.type { - case .string: - return self.object as? String ?? "" - case .number: - return self.rawNumber.stringValue - case .bool: - return (self.object as? Bool).map { String($0) } ?? "" - default: - return "" + switch type { + case .string: return object as? String ?? "" + case .number: return rawNumber.stringValue + case .bool: return (object as? Bool).map { String($0) } ?? "" + default: return "" } } set { - self.object = NSString(string: newValue) + object = newValue } } } @@ -880,40 +808,31 @@ extension JSON { //Optional number public var number: NSNumber? { get { - switch self.type { - case .number: - return self.rawNumber - case .bool: - return NSNumber(value: self.rawBool ? 1 : 0) - default: - return nil + switch type { + case .number: return rawNumber + case .bool: return NSNumber(value: rawBool ? 1 : 0) + default: return nil } } set { - self.object = newValue ?? NSNull() + object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { - switch self.type { + switch type { case .string: - let decimal = NSDecimalNumber(string: self.object as? String) - if decimal == NSDecimalNumber.notANumber { // indicates parse error - return NSDecimalNumber.zero - } - return decimal - case .number: - return self.object as? NSNumber ?? NSNumber(value: 0) - case .bool: - return NSNumber(value: self.rawBool ? 1 : 0) - default: - return NSNumber(value: 0.0) + let decimal = NSDecimalNumber(string: object as? String) + return decimal == .notANumber ? .zero : decimal + case .number: return object as? NSNumber ?? NSNumber(value: 0) + case .bool: return NSNumber(value: rawBool ? 1 : 0) + default: return NSNumber(value: 0.0) } } set { - self.object = newValue + object = newValue } } } @@ -923,17 +842,15 @@ extension JSON { extension JSON { public var null: NSNull? { + set { + object = NSNull() + } get { - switch self.type { - case .null: - return self.rawNull - default: - return nil + switch type { + case .null: return rawNull + default: return nil } } - set { - self.object = NSNull() - } } public func exists() -> Bool { if let errorValue = error, (400...1000).contains(errorValue.errorCode) { @@ -950,12 +867,12 @@ extension JSON { //Optional URL public var url: URL? { get { - switch self.type { + switch type { case .string: // Check for existing percent escapes first to prevent double-escaping of % character - if self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { - return Foundation.URL(string: self.rawString) - } else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { + if rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { + return Foundation.URL(string: rawString) + } else if let encodedString_ = rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. return Foundation.URL(string: encodedString_) } else { @@ -966,7 +883,7 @@ extension JSON { } } set { - self.object = newValue?.absoluteString ?? NSNull() + object = newValue?.absoluteString ?? NSNull() } } } @@ -977,265 +894,265 @@ extension JSON { public var double: Double? { get { - return self.number?.doubleValue + return number?.doubleValue } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var doubleValue: Double { get { - return self.numberValue.doubleValue + return numberValue.doubleValue } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var float: Float? { get { - return self.number?.floatValue + return number?.floatValue } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var floatValue: Float { get { - return self.numberValue.floatValue + return numberValue.floatValue } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var int: Int? { get { - return self.number?.intValue + return number?.intValue } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var intValue: Int { get { - return self.numberValue.intValue + return numberValue.intValue } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var uInt: UInt? { get { - return self.number?.uintValue + return number?.uintValue } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var uIntValue: UInt { get { - return self.numberValue.uintValue + return numberValue.uintValue } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var int8: Int8? { get { - return self.number?.int8Value + return number?.int8Value } set { if let newValue = newValue { - self.object = NSNumber(value: Int(newValue)) + object = NSNumber(value: Int(newValue)) } else { - self.object = NSNull() + object = NSNull() } } } public var int8Value: Int8 { get { - return self.numberValue.int8Value + return numberValue.int8Value } set { - self.object = NSNumber(value: Int(newValue)) + object = NSNumber(value: Int(newValue)) } } public var uInt8: UInt8? { get { - return self.number?.uint8Value + return number?.uint8Value } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var uInt8Value: UInt8 { get { - return self.numberValue.uint8Value + return numberValue.uint8Value } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var int16: Int16? { get { - return self.number?.int16Value + return number?.int16Value } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var int16Value: Int16 { get { - return self.numberValue.int16Value + return numberValue.int16Value } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { - return self.number?.uint16Value + return number?.uint16Value } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var uInt16Value: UInt16 { get { - return self.numberValue.uint16Value + return numberValue.uint16Value } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var int32: Int32? { get { - return self.number?.int32Value + return number?.int32Value } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var int32Value: Int32 { get { - return self.numberValue.int32Value + return numberValue.int32Value } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { - return self.number?.uint32Value + return number?.uint32Value } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var uInt32Value: UInt32 { get { - return self.numberValue.uint32Value + return numberValue.uint32Value } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var int64: Int64? { get { - return self.number?.int64Value + return number?.int64Value } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var int64Value: Int64 { get { - return self.numberValue.int64Value + return numberValue.int64Value } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { - return self.number?.uint64Value + return number?.uint64Value } set { if let newValue = newValue { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } else { - self.object = NSNull() + object = NSNull() } } } public var uInt64Value: UInt64 { get { - return self.numberValue.uint64Value + return numberValue.uint64Value } set { - self.object = NSNumber(value: newValue) + object = NSNumber(value: newValue) } } } @@ -1247,84 +1164,57 @@ extension JSON: Swift.Comparable {} public func == (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber == rhs.rawNumber - case (.string, .string): - return lhs.rawString == rhs.rawString - case (.bool, .bool): - return lhs.rawBool == rhs.rawBool - case (.array, .array): - return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.dictionary, .dictionary): - return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.null, .null): - return true - default: - return false + case (.number, .number): return lhs.rawNumber == rhs.rawNumber + case (.string, .string): return lhs.rawString == rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false } } public func <= (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber <= rhs.rawNumber - case (.string, .string): - return lhs.rawString <= rhs.rawString - case (.bool, .bool): - return lhs.rawBool == rhs.rawBool - case (.array, .array): - return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.dictionary, .dictionary): - return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.null, .null): - return true - default: - return false + case (.number, .number): return lhs.rawNumber <= rhs.rawNumber + case (.string, .string): return lhs.rawString <= rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false } } public func >= (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber >= rhs.rawNumber - case (.string, .string): - return lhs.rawString >= rhs.rawString - case (.bool, .bool): - return lhs.rawBool == rhs.rawBool - case (.array, .array): - return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.dictionary, .dictionary): - return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.null, .null): - return true - default: - return false + case (.number, .number): return lhs.rawNumber >= rhs.rawNumber + case (.string, .string): return lhs.rawString >= rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false } } public func > (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber > rhs.rawNumber - case (.string, .string): - return lhs.rawString > rhs.rawString - default: - return false + case (.number, .number): return lhs.rawNumber > rhs.rawNumber + case (.string, .string): return lhs.rawString > rhs.rawString + default: return false } } public func < (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { - case (.number, .number): - return lhs.rawNumber < rhs.rawNumber - case (.string, .string): - return lhs.rawString < rhs.rawString - default: - return false + case (.number, .number): return lhs.rawNumber < rhs.rawNumber + case (.string, .string): return lhs.rawString < rhs.rawString + default: return false } } @@ -1348,12 +1238,9 @@ extension NSNumber { func == (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == .orderedSame + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == .orderedSame } } @@ -1364,48 +1251,36 @@ func != (lhs: NSNumber, rhs: NSNumber) -> Bool { func < (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == .orderedAscending + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == .orderedAscending } } func > (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) == ComparisonResult.orderedDescending + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) != .orderedDescending + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) != .orderedDescending } } func >= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { - case (false, true): - return false - case (true, false): - return false - default: - return lhs.compare(rhs) != .orderedAscending + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) != .orderedAscending } } diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index d486f0a1..db895774 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -13,5 +13,5 @@ Pod::Spec.new do |s| s.watchos.deployment_target = "3.0" s.tvos.deployment_target = "9.0" s.source = { :git => "https://github.com/SwiftyJSON/SwiftyJSON.git", :tag => s.version } - s.source_files = "Source/*.swift" + s.source_files = "Source/SwiftyJSON/*.swift" end From bad5f2f94a71216a32c030a3586bdcfc1f7e660b Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Mon, 15 Apr 2019 23:01:18 +0800 Subject: [PATCH 231/260] Bump to 5.0.0 --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index db895774..c12cfbd8 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "4.3.0" + s.version = "5.0.0" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } From d68db819a15f70dfc00d000977d4e64ce25a8b58 Mon Sep 17 00:00:00 2001 From: Tony Klausing Date: Fri, 6 Mar 2020 15:11:29 -0600 Subject: [PATCH 232/260] removed broken link --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 7a10e29c..49a5f64e 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,6 @@ Platform | Build Status 6. [Work with Moya](#work-with-moya) 7. [SwiftyJSON Model Generator](#swiftyjson-model-generator) -> [中文介绍](http://tangplin.github.io/swiftyjson/) - ## Why is the typical JSON handling in Swift NOT good? From 774f1e2b01b16e7e399b4e057d2f7b9c8526ba1a Mon Sep 17 00:00:00 2001 From: Denys Telezhkin Date: Tue, 11 Aug 2020 13:21:06 +0300 Subject: [PATCH 233/260] Bump iOS deployment target to iOS 9. Remove platforms from Package.swift. --- Package.swift | 3 --- SwiftyJSON.podspec | 2 +- SwiftyJSON.xcodeproj/project.pbxproj | 10 ++++------ 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/Package.swift b/Package.swift index 1a60e2e7..744e95dd 100644 --- a/Package.swift +++ b/Package.swift @@ -3,9 +3,6 @@ import PackageDescription let package = Package( name: "SwiftyJSON", - platforms: [ - .macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v3) - ], products: [ .library(name: "SwiftyJSON", targets: ["SwiftyJSON"]) ], diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index c12cfbd8..bd821743 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -9,7 +9,7 @@ Pod::Spec.new do |s| s.requires_arc = true s.swift_version = "5.0" s.osx.deployment_target = "10.9" - s.ios.deployment_target = "8.0" + s.ios.deployment_target = "9.0" s.watchos.deployment_target = "3.0" s.tvos.deployment_target = "9.0" s.source = { :git => "https://github.com/SwiftyJSON/SwiftyJSON.git", :tag => s.version } diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 8160930b..c831948d 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -767,7 +767,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; MACOSX_DEPLOYMENT_TARGET = 10.9; METAL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; @@ -822,7 +822,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; MACOSX_DEPLOYMENT_TARGET = 10.9; METAL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; @@ -849,7 +849,7 @@ GCC_OPTIMIZATION_LEVEL = 0; INFOPLIST_FILE = "Source/Info-iOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; @@ -874,7 +874,7 @@ GCC_OPTIMIZATION_LEVEL = s; INFOPLIST_FILE = "Source/Info-iOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; @@ -937,7 +937,6 @@ GCC_OPTIMIZATION_LEVEL = 0; INFOPLIST_FILE = "Source/Info-tvOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; @@ -964,7 +963,6 @@ GCC_OPTIMIZATION_LEVEL = s; INFOPLIST_FILE = "Source/Info-tvOS.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.swiftyjson.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = SwiftyJSON; From 70067f581fceb94bcda070762279025515e6b365 Mon Sep 17 00:00:00 2001 From: H3RSKO <34112131+H3RSKO@users.noreply.github.com> Date: Sun, 16 Aug 2020 13:27:18 -0400 Subject: [PATCH 234/260] Updated Readme Fixed sentence structure and typo in readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 49a5f64e..24654150 100644 --- a/README.md +++ b/README.md @@ -464,7 +464,7 @@ If both JSONs contain a value for the same key, _mostly_ this value gets overwri - In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. - In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. -In case, where two fields in a JSON have a different types, the value will get always overwritten. +In a case where two fields in a JSON have different types, the value will get always overwritten. There are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy. From b3dcd7dbd0d488e1a7077cb33b00f2083e382f07 Mon Sep 17 00:00:00 2001 From: Kyle Fang Date: Sun, 28 Mar 2021 07:46:13 +0800 Subject: [PATCH 235/260] chore: bump cocoapods version --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index bd821743..944a24b7 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "5.0.0" + s.version = "5.0.1" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } From 69c58e20d11991516ac9f0f3496f252bf067295f Mon Sep 17 00:00:00 2001 From: Lewis Smith Date: Fri, 2 Apr 2021 09:16:50 +0100 Subject: [PATCH 236/260] fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 24654150..a4cd321f 100644 --- a/README.md +++ b/README.md @@ -396,7 +396,7 @@ let json: JSON = "I'm a json" ``` ```swift -/ /IntegerLiteralConvertible +// IntegerLiteralConvertible let json: JSON = 12345 ``` From 84bf7837a3da22099567b737899b98af15c37a67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Dahlgren?= Date: Tue, 15 Mar 2022 16:29:48 +0100 Subject: [PATCH 237/260] Reorder build phases to fix Xcode 13.3 issue --- SwiftyJSON.xcodeproj/project.pbxproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index c831948d..3f48deaa 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -328,9 +328,9 @@ isa = PBXNativeTarget; buildConfigurationList = 2E4FEFF119575BE100351305 /* Build configuration list for PBXNativeTarget "SwiftyJSON iOS" */; buildPhases = ( + 2E4FEFD819575BE100351305 /* Headers */, 2E4FEFD619575BE100351305 /* Sources */, 2E4FEFD719575BE100351305 /* Frameworks */, - 2E4FEFD819575BE100351305 /* Headers */, 2E4FEFD919575BE100351305 /* Resources */, ); buildRules = ( @@ -364,9 +364,9 @@ isa = PBXNativeTarget; buildConfigurationList = 7236B4F31BAC14150020529B /* Build configuration list for PBXNativeTarget "SwiftyJSON tvOS" */; buildPhases = ( + 7236B4F01BAC14150020529B /* Headers */, 7236B4ED1BAC14150020529B /* Sources */, 7236B4EF1BAC14150020529B /* Frameworks */, - 7236B4F01BAC14150020529B /* Headers */, 7236B4F21BAC14150020529B /* Resources */, ); buildRules = ( @@ -382,9 +382,9 @@ isa = PBXNativeTarget; buildConfigurationList = 9C7DFC6E1A9102BD005AA3F7 /* Build configuration list for PBXNativeTarget "SwiftyJSON macOS" */; buildPhases = ( + 9C7DFC581A9102BD005AA3F7 /* Headers */, 9C7DFC561A9102BD005AA3F7 /* Sources */, 9C7DFC571A9102BD005AA3F7 /* Frameworks */, - 9C7DFC581A9102BD005AA3F7 /* Headers */, 9C7DFC591A9102BD005AA3F7 /* Resources */, ); buildRules = ( @@ -436,9 +436,9 @@ isa = PBXNativeTarget; buildConfigurationList = E4D7CCE51B9465A700EE7221 /* Build configuration list for PBXNativeTarget "SwiftyJSON watchOS" */; buildPhases = ( + E4D7CCE21B9465A700EE7221 /* Headers */, E4D7CCDF1B9465A700EE7221 /* Sources */, E4D7CCE11B9465A700EE7221 /* Frameworks */, - E4D7CCE21B9465A700EE7221 /* Headers */, E4D7CCE41B9465A700EE7221 /* Resources */, ); buildRules = ( From 764c0c8b944574cd63592a452c23865f54b66d0d Mon Sep 17 00:00:00 2001 From: Luo Xiu Date: Mon, 31 Oct 2022 18:34:10 +0800 Subject: [PATCH 238/260] fix compile warning, which will be compile error in upcoming swift 6 --- Source/SwiftyJSON/SwiftyJSON.swift | 2 +- Tests/SwiftJSONTests/RawRepresentableTests.swift | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index f7a3f085..e625810e 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -236,7 +236,7 @@ public struct JSON { rawString = string case _ as NSNull: type = .null - case nil: + case Optional.none: type = .null case let array as [Any]: type = .array diff --git a/Tests/SwiftJSONTests/RawRepresentableTests.swift b/Tests/SwiftJSONTests/RawRepresentableTests.swift index 9c628a05..88a70de8 100644 --- a/Tests/SwiftJSONTests/RawRepresentableTests.swift +++ b/Tests/SwiftJSONTests/RawRepresentableTests.swift @@ -84,6 +84,12 @@ class RawRepresentableTests: XCTestCase { if JSON(rawValue: NSObject()) != nil { XCTFail("Should not run into here") } + + do { + let n: Int? = nil + let json = JSON(n as Any) + XCTAssertEqual(json.type, .null) + } } func testArray() { From d60a635197cfe3a36440a6768c3d94563fae3ee8 Mon Sep 17 00:00:00 2001 From: Antoine Bollengier <44288655+b5i@users.noreply.github.com> Date: Tue, 20 Jun 2023 10:43:52 +0200 Subject: [PATCH 239/260] Added better readability to a comment --- Source/SwiftyJSON/SwiftyJSON.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index e625810e..6e1b9ded 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -433,7 +433,7 @@ extension JSON { Example: - ``` + ```swift let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] From c27a45e6386fc869d0e0f23eda1ef61104d2770e Mon Sep 17 00:00:00 2001 From: Antoine Bollengier <44288655+b5i@users.noreply.github.com> Date: Tue, 20 Jun 2023 10:49:02 +0200 Subject: [PATCH 240/260] Comments --- Source/SwiftyJSON/SwiftyJSON.swift | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index 6e1b9ded..c8be53c2 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -467,10 +467,14 @@ extension JSON { Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: - + ```swift let name = json[9,"list","person","name"] - - The same as: let name = json[9]["list"]["person"]["name"] + ``` + + The same as: + ```swift + let name = json[9]["list"]["person"]["name"] + ``` - returns: Return a json found by the path or a null json with error */ From c8ae6e331dba0627181d0fd91e3c844070dd628a Mon Sep 17 00:00:00 2001 From: Will Jessop Date: Thu, 10 Aug 2023 10:57:32 -0400 Subject: [PATCH 241/260] Add info on removing dictionary keys in place --- README.md | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/README.md b/README.md index a4cd321f..0b3fc855 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Platform | Build Status - [Raw object](#raw-object) - [Literal convertibles](#literal-convertibles) - [Merging](#merging) + - [Removing elements](#removing-elements) 5. [Work with Alamofire](#work-with-alamofire) 6. [Work with Moya](#work-with-moya) 7. [SwiftyJSON Model Generator](#swiftyjson-model-generator) @@ -503,6 +504,69 @@ let updated = original.merge(with: update) // ] ``` + +#### Removing elements + +If you are storing dictionaries, you can remove elements using `dictionaryObject.removeValue(forKey:)`. This mutates the JSON object in place. + +For example: + +```swift +var object = JSON([ + "one": ["color": "blue"], + "two": ["city": "tokyo", + "country": "japan", + "foods": [ + "breakfast": "tea", + "lunch": "sushi" + ] + ] +]) +``` + +Lets remove the `country` key: + +```swift +object["two"].dictionaryObject?.removeValue(forKey: "country") +``` + +If you `print(object)`, you'll see that the `country` key no longer exists. + +```json +{ + "one" : { + "color" : "blue" + }, + "two" : { + "city" : "tokyo", + "foods" : { + "breakfast" : "tea", + "lunch" : "sushi" + } + } +} +``` + +This also works for nested dictionaries: + +```swift +object["two"]["foods"].dictionaryObject?.removeValue(forKey: "breakfast") +``` + +```json +{ + "one" : { + "color" : "blue" + }, + "two" : { + "city" : "tokyo", + "foods" : { + "lunch" : "sushi" + } + } +} +``` + ## String representation There are two options available: - use the default Swift one From 75441b91f55b46037da50bb528f6b66b5491465a Mon Sep 17 00:00:00 2001 From: Annie Gupta Date: Thu, 18 Jan 2024 00:39:33 +0530 Subject: [PATCH 242/260] Errors in readme #1144 Fixed errors in README.MD Issue #1144 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a4cd321f..d87739bb 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ An unreadable mess--for something that should really be simple! With SwiftyJSON all you have to do is: ```swift -let json = JSON(data: dataFromNetworking) +let json = try? JSON(data: dataFromNetworking) if let userName = json[0]["user"]["name"].string { //Now you got your value } @@ -70,7 +70,7 @@ if let userName = json[0]["user"]["name"].string { And don't worry about the Optional Wrapping thing. It's done for you automatically. ```swift -let json = JSON(data: dataFromNetworking) +let json = try? JSON(data: dataFromNetworking) let result = json[999999]["wrong_key"]["wrong_name"] if let userName = result.string { //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety @@ -143,7 +143,7 @@ import SwiftyJSON ``` ```swift -let json = JSON(data: dataFromNetworking) +let json = try? JSON(data: dataFromNetworking) ``` Or From 4c42874b2f2fb5eaa66afcc0c463f36bf92ea407 Mon Sep 17 00:00:00 2001 From: Nathan Molby Date: Tue, 19 Mar 2024 12:58:04 -0400 Subject: [PATCH 243/260] Add privacy manifest --- Package.swift | 9 +++++++-- Source/SwiftyJSON/PrivacyInfo.xcprivacy | 14 ++++++++++++++ SwiftyJSON.podspec | 1 + 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 Source/SwiftyJSON/PrivacyInfo.xcprivacy diff --git a/Package.swift b/Package.swift index 744e95dd..1fdaf06c 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.3 import PackageDescription let package = Package( @@ -7,7 +7,12 @@ let package = Package( .library(name: "SwiftyJSON", targets: ["SwiftyJSON"]) ], targets: [ - .target(name: "SwiftyJSON", dependencies: []), + .target(name: "SwiftyJSON", + dependencies: [], + resources: [ + .copy("PrivacyInfo.xcprivacy") + ] + ), .testTarget(name: "SwiftJSONTests", dependencies: ["SwiftyJSON"]) ], swiftLanguageVersions: [.v5] diff --git a/Source/SwiftyJSON/PrivacyInfo.xcprivacy b/Source/SwiftyJSON/PrivacyInfo.xcprivacy new file mode 100644 index 00000000..d37d6275 --- /dev/null +++ b/Source/SwiftyJSON/PrivacyInfo.xcprivacy @@ -0,0 +1,14 @@ + + + + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + NSPrivacyTrackingDomains + + NSPrivacyTracking + + + diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 944a24b7..83f6f3b0 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -14,4 +14,5 @@ Pod::Spec.new do |s| s.tvos.deployment_target = "9.0" s.source = { :git => "https://github.com/SwiftyJSON/SwiftyJSON.git", :tag => s.version } s.source_files = "Source/SwiftyJSON/*.swift" + s.resource_bundles = {'SwiftyJSON' => ['Source/SwiftyJSON/PrivacyInfo.xcprivacy']} end From af76cf3ef710b6ca5f8c05f3a31307d44a3c5828 Mon Sep 17 00:00:00 2001 From: Zigii Wong Date: Wed, 27 Mar 2024 22:05:55 +0800 Subject: [PATCH 244/260] Version Bump to 5.0.2 --- SwiftyJSON.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.podspec b/SwiftyJSON.podspec index 83f6f3b0..dd091231 100644 --- a/SwiftyJSON.podspec +++ b/SwiftyJSON.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = "SwiftyJSON" - s.version = "5.0.1" + s.version = "5.0.2" s.summary = "SwiftyJSON makes it easy to deal with JSON data in Swift" s.homepage = "https://github.com/SwiftyJSON/SwiftyJSON" s.license = { :type => "MIT" } From be72f800ceb3ef6d2e618e2be50d37ad7e0e094f Mon Sep 17 00:00:00 2001 From: Blazej SLEBODA <5544365+Adobels@users.noreply.github.com> Date: Thu, 11 Apr 2024 15:18:57 +0200 Subject: [PATCH 245/260] Fix missing PrivacyInfo.xcprivacy in xcodeproj file --- SwiftyJSON.xcodeproj/project.pbxproj | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index 3f48deaa..ec223336 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -51,6 +51,10 @@ 9C459F041A9103C1008C9A41 /* DictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8B66C8B19E51D6500540692 /* DictionaryTests.swift */; }; 9C459F051A9103C1008C9A41 /* ArrayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8B66C8D19E52F4200540692 /* ArrayTests.swift */; }; 9C7DFC661A9102BD005AA3F7 /* SwiftyJSON.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9C7DFC5B1A9102BD005AA3F7 /* SwiftyJSON.framework */; }; + A1DE64C62BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = A1DE64C52BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy */; }; + A1DE64C72BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = A1DE64C52BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy */; }; + A1DE64C82BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = A1DE64C52BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy */; }; + A1DE64C92BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = A1DE64C52BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy */; }; A819C49719E1A7DD00ADCC3D /* LiteralConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A819C49619E1A7DD00ADCC3D /* LiteralConvertibleTests.swift */; }; A819C49919E1B10300ADCC3D /* RawRepresentableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A819C49819E1B10300ADCC3D /* RawRepresentableTests.swift */; }; A819C49F19E2EE5B00ADCC3D /* SubscriptTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */; }; @@ -126,6 +130,7 @@ 9C459EF61A9103B1008C9A41 /* Info-macOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "Info-macOS.plist"; path = "../Info-macOS.plist"; sourceTree = ""; }; 9C7DFC5B1A9102BD005AA3F7 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 9C7DFC651A9102BD005AA3F7 /* SwiftyJSON macOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON macOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + A1DE64C52BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; name = PrivacyInfo.xcprivacy; path = SwiftyJSON/PrivacyInfo.xcprivacy; sourceTree = ""; }; A819C49619E1A7DD00ADCC3D /* LiteralConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = LiteralConvertibleTests.swift; path = ../SwiftJSONTests/LiteralConvertibleTests.swift; sourceTree = ""; }; A819C49819E1B10300ADCC3D /* RawRepresentableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RawRepresentableTests.swift; path = ../SwiftJSONTests/RawRepresentableTests.swift; sourceTree = ""; }; A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SubscriptTests.swift; path = ../SwiftJSONTests/SubscriptTests.swift; sourceTree = ""; }; @@ -241,6 +246,7 @@ 2E4FEFDE19575BE100351305 /* Supporting Files */ = { isa = PBXGroup; children = ( + A1DE64C52BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy */, 2E4FEFDF19575BE100351305 /* Info-iOS.plist */, 030B6CDC1A6E171D00C2D4F1 /* Info-macOS.plist */, E4D7CCE91B9465A800EE7221 /* Info-watchOS.plist */, @@ -527,6 +533,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + A1DE64C62BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -542,6 +549,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + A1DE64C92BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -549,6 +557,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + A1DE64C72BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -572,6 +581,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + A1DE64C82BC7D95C0097BCE6 /* PrivacyInfo.xcprivacy in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; From ed2bedd6f804b0dd65b03b0cd68d9b2e9909130c Mon Sep 17 00:00:00 2001 From: Brandon Fraune <52302810+fraune@users.noreply.github.com> Date: Tue, 21 May 2024 12:39:35 -0500 Subject: [PATCH 246/260] Update .swiftlint.yml Resolve SwiftLint warning: `'variable_name' has been renamed to 'identifier_name' and will be completely removed in a future release.` --- .swiftlint.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index 03003d1d..36ee05ac 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -1,7 +1,7 @@ disabled_rules: - force_cast - force_try - - variable_name + - identifier_name - type_name - file_length - line_length From d0058a7b750f769b37e00de4e2546bec85ab55c0 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sat, 10 Aug 2024 19:21:22 +0200 Subject: [PATCH 247/260] Delete .travis.yml -- Travis CI is no longer free to open source https://app.travis-ci.com/github/SwiftyJSON --- .travis.yml | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 17140ab1..00000000 --- a/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: objective-c -osx_image: xcode10.2 -xcode_sdk: iphonesimulator12.0 -script: -- set -o pipefail -- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON iOS" -destination "platform=iOS Simulator,name=iPhone 6" build-for-testing test | xcpretty -- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON macOS" build-for-testing test | xcpretty -- travis_retry xcodebuild -workspace SwiftyJSON.xcworkspace -scheme "SwiftyJSON tvOS" -destination "platform=tvOS Simulator,name=Apple TV" build-for-testing test | xcpretty From 06fcc37fb14d80d6130621bf6f9940f4d601023a Mon Sep 17 00:00:00 2001 From: Joe Ferrucci <2114494+JoeFerrucci@users.noreply.github.com> Date: Wed, 23 Oct 2024 12:51:47 -0500 Subject: [PATCH 248/260] Remove spam URL URL is outdated and leads to spammy/phishy site through redirects. --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index d87739bb..c92bb44e 100644 --- a/README.md +++ b/README.md @@ -556,5 +556,4 @@ provider.request(.showProducts) { result in ## SwiftyJSON Model Generator Tools to generate SwiftyJSON Models -* [JSON Cafe](http://www.jsoncafe.com/) * [JSON Export](https://github.com/Ahmed-Ali/JSONExport) From b00fb02693b50122ef83894afd1846074e572e6a Mon Sep 17 00:00:00 2001 From: Antoine Bollengier <44288655+b5i@users.noreply.github.com> Date: Mon, 26 May 2025 22:30:16 +0200 Subject: [PATCH 249/260] perf: improve unwrap method performance by using native `mapValues` Around 10% better performance on tests, 20% on "real-world" usage. --- Source/SwiftyJSON/SwiftyJSON.swift | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index c8be53c2..ec1822b9 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -265,11 +265,7 @@ private func unwrap(_ object: Any) -> Any { case let array as [Any]: return array.map(unwrap) case let dictionary as [String: Any]: - var d = dictionary - dictionary.forEach { pair in - d[pair.key] = unwrap(pair.value) - } - return d + return dictionary.mapValues(unwrap) default: return object } From 76f8d81bf1c300ddec2704cdc6fc2dd06b1313fd Mon Sep 17 00:00:00 2001 From: Antoine Bollengier <44288655+b5i@users.noreply.github.com> Date: Mon, 26 May 2025 23:16:49 +0200 Subject: [PATCH 250/260] perf: improve dictionnary property getter by using native `mapValues` Around 8% better on tests. --- Source/SwiftyJSON/SwiftyJSON.swift | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index ec1822b9..1da9e58f 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -705,11 +705,7 @@ extension JSON { //Optional [String : JSON] public var dictionary: [String: JSON]? { if type == .dictionary { - var d = [String: JSON](minimumCapacity: rawDictionary.count) - rawDictionary.forEach { pair in - d[pair.key] = JSON(pair.value) - } - return d + return rawDictionary.mapValues(JSON.init(_:)) } else { return nil } From 45c240c76951c27f0aa39d63bfc02ef02943a10b Mon Sep 17 00:00:00 2001 From: Antoine Bollengier <44288655+b5i@users.noreply.github.com> Date: Mon, 26 May 2025 23:35:06 +0200 Subject: [PATCH 251/260] perf: improve performance of `dictionaryLiteral` initializer of JSON --- Source/SwiftyJSON/SwiftyJSON.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index 1da9e58f..6e0904ac 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -524,7 +524,7 @@ extension JSON: Swift.ExpressibleByFloatLiteral { extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { - let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1}) + let dictionary = Dictionary(elements, uniquingKeysWith: { $1 }) self.init(dictionary) } } From c9d0f9d8ccb5f68af4915ff6dafa55a1c17f1001 Mon Sep 17 00:00:00 2001 From: Antoine Bollengier <44288655+b5i@users.noreply.github.com> Date: Mon, 26 May 2025 23:43:34 +0200 Subject: [PATCH 252/260] perf: improve performance of `array` property getter by removing use of closure in map function --- Source/SwiftyJSON/SwiftyJSON.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index 6e0904ac..7b4ff42f 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -676,7 +676,7 @@ extension JSON { //Optional [JSON] public var array: [JSON]? { - return type == .array ? rawArray.map { JSON($0) } : nil + return type == .array ? rawArray.map(JSON.init(_:)) : nil } //Non-optional [JSON] From ae7ca8b3d404a1b24e23cb5c927ddc6cbdfbf7fa Mon Sep 17 00:00:00 2001 From: Antoine Bollengier <44288655+b5i@users.noreply.github.com> Date: Mon, 26 May 2025 23:53:49 +0200 Subject: [PATCH 253/260] perf: remove use of closure in `stringValue` property getter --- Source/SwiftyJSON/SwiftyJSON.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index 7b4ff42f..97daf4fc 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -787,7 +787,7 @@ extension JSON { switch type { case .string: return object as? String ?? "" case .number: return rawNumber.stringValue - case .bool: return (object as? Bool).map { String($0) } ?? "" + case .bool: return (object as? Bool).map(String.init) ?? "" default: return "" } } From ef6d3592a29a1e3cc7c7a6f187523da7682d0799 Mon Sep 17 00:00:00 2001 From: wongzigii Date: Tue, 27 May 2025 15:32:20 +0800 Subject: [PATCH 254/260] Enable GitHub Action CI and fix tests --- .github/workflows/ci.yml | 25 ++++++++++++++++++++ Package.swift | 8 ++++++- Tests/SwiftJSONTests/BaseTests.swift | 4 ++-- Tests/SwiftJSONTests/PerformanceTests.swift | 4 ++-- Tests/SwiftJSONTests/SequenceTypeTests.swift | 8 ++++--- Tests/{Tes => SwiftJSONTests}/Tests.json | 0 6 files changed, 41 insertions(+), 8 deletions(-) create mode 100644 .github/workflows/ci.yml rename Tests/{Tes => SwiftJSONTests}/Tests.json (100%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..2680e910 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +name: CI + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build-and-test: + runs-on: macos-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Swift + uses: swift-actions/setup-swift@v2 + with: + swift-version: '6.0' + + - name: Build + run: swift build --build-tests + + - name: Run tests + run: swift test \ No newline at end of file diff --git a/Package.swift b/Package.swift index 1fdaf06c..ba89fb5f 100644 --- a/Package.swift +++ b/Package.swift @@ -13,7 +13,13 @@ let package = Package( .copy("PrivacyInfo.xcprivacy") ] ), - .testTarget(name: "SwiftJSONTests", dependencies: ["SwiftyJSON"]) + .testTarget( + name: "SwiftJSONTests", + dependencies: ["SwiftyJSON"], + resources: [ + .copy("Tests.json") + ] + ) ], swiftLanguageVersions: [.v5] ) diff --git a/Tests/SwiftJSONTests/BaseTests.swift b/Tests/SwiftJSONTests/BaseTests.swift index 9139c204..634e1c8b 100644 --- a/Tests/SwiftJSONTests/BaseTests.swift +++ b/Tests/SwiftJSONTests/BaseTests.swift @@ -33,8 +33,8 @@ class BaseTests: XCTestCase { // let file = "./Tests/Tes/Tests.json" // self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) - if let file = Bundle(for: BaseTests.self).path(forResource: "Tests", ofType: "json") { - self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) + if let file = Bundle.module.url(forResource: "Tests", withExtension: "json") { + self.testData = try? Data(contentsOf: file) } else { XCTFail("Can't find the test JSON file") } diff --git a/Tests/SwiftJSONTests/PerformanceTests.swift b/Tests/SwiftJSONTests/PerformanceTests.swift index 7535f7d8..70f1f2f2 100644 --- a/Tests/SwiftJSONTests/PerformanceTests.swift +++ b/Tests/SwiftJSONTests/PerformanceTests.swift @@ -30,8 +30,8 @@ class PerformanceTests: XCTestCase { override func setUp() { super.setUp() - if let file = Bundle(for: PerformanceTests.self).path(forResource: "Tests", ofType: "json") { - self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) + if let file = Bundle.module.url(forResource: "Tests", withExtension: "json") { + self.testData = try? Data(contentsOf: file) } else { XCTFail("Can't find the test JSON file") } diff --git a/Tests/SwiftJSONTests/SequenceTypeTests.swift b/Tests/SwiftJSONTests/SequenceTypeTests.swift index d0d8cadd..557c3dbb 100644 --- a/Tests/SwiftJSONTests/SequenceTypeTests.swift +++ b/Tests/SwiftJSONTests/SequenceTypeTests.swift @@ -25,10 +25,12 @@ import SwiftyJSON class SequenceTypeTests: XCTestCase { + var testData: Data? + func testJSONFile() { - if let file = Bundle(for: BaseTests.self).path(forResource: "Tests", ofType: "json") { - let testData = try? Data(contentsOf: URL(fileURLWithPath: file)) - guard let json = try? JSON(data: testData!) else { + if let file = Bundle.module.url(forResource: "Tests", withExtension: "json") { + self.testData = try? Data(contentsOf: file) + guard let json = try? JSON(data: self.testData!) else { XCTFail("Unable to parse the data") return } diff --git a/Tests/Tes/Tests.json b/Tests/SwiftJSONTests/Tests.json similarity index 100% rename from Tests/Tes/Tests.json rename to Tests/SwiftJSONTests/Tests.json From 9f751e8dca235d35954edebf943662dbf94d160c Mon Sep 17 00:00:00 2001 From: wongzigii Date: Tue, 27 May 2025 15:39:51 +0800 Subject: [PATCH 255/260] Update README CI Badge --- README.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 58aeb989..e1740680 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,11 @@ # SwiftyJSON +[![CI](https://github.com/SwiftyJSON/SwiftyJSON/actions/workflows/ci.yml/badge.svg)](https://github.com/SwiftyJSON/SwiftyJSON/actions/workflows/ci.yml) + [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com) SwiftyJSON makes it easy to deal with JSON data in Swift. -Platform | Build Status ----------| --------------| -*OS | [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) | -[Linux](https://github.com/IBM-Swift/SwiftyJSON) | [![Build Status](https://travis-ci.org/IBM-Swift/SwiftyJSON.svg?branch=master)](https://travis-ci.org/IBM-Swift/SwiftyJSON) | - - 1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) 2. [Requirements](#requirements) 3. [Integration](#integration) From f02c453bb544085109a02f2f2fe8f2cfb0b7f6e8 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Sun, 25 Jan 2026 21:14:51 -0700 Subject: [PATCH 256/260] Add Swift 6 support with Sendable conformance - Update Package.swift to swift-tools-version:6.0 - Remove swiftLanguageVersions lock - Add @unchecked Sendable to JSON struct - Add Sendable to Type, SwiftyJSONError, JSONKey enums - Add comprehensive concurrency tests (18 tests) - Update README requirements and CHANGELOG The JSON type can now safely cross actor boundaries in Swift 6 concurrency. Closes #1163 --- CHANGELOG.md | 9 + Package.swift | 5 +- README.md | 3 +- Source/SwiftyJSON/SwiftyJSON.swift | 8 +- Tests/SwiftJSONTests/ConcurrencyTests.swift | 386 ++++++++++++++++++++ 5 files changed, 403 insertions(+), 8 deletions(-) create mode 100644 Tests/SwiftJSONTests/ConcurrencyTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a0935d3..082b0247 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ [Full Changelog](https://github.com/SwiftyJSON/SwiftyJSON/compare/2.2.0...HEAD) +### Added +- Swift 6 support with full Sendable conformance ([#1163](https://github.com/SwiftyJSON/SwiftyJSON/issues/1163)) +- Comprehensive concurrency tests for actor boundary validation + +### Changed +- `JSON` struct conforms to `@unchecked Sendable` +- `Type`, `SwiftyJSONError`, `JSONKey` enums conform to `Sendable` +- Minimum Swift tools version updated to 6.0 + **Closed issues:** - 156 compiler errors Mavericks + Xcode 6.2 [\#220](https://github.com/SwiftyJSON/SwiftyJSON/issues/220) diff --git a/Package.swift b/Package.swift index ba89fb5f..fb026e55 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.3 +// swift-tools-version:6.0 import PackageDescription let package = Package( @@ -20,6 +20,5 @@ let package = Package( .copy("Tests.json") ] ) - ], - swiftLanguageVersions: [.v5] + ] ) diff --git a/README.md b/README.md index e1740680..a6f3037a 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,8 @@ if let userName = result.string { ## Requirements - iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+ -- Xcode 8 +- Xcode 16+ +- Swift 6.0+ ## Integration diff --git a/Source/SwiftyJSON/SwiftyJSON.swift b/Source/SwiftyJSON/SwiftyJSON.swift index 97daf4fc..d2f39ef2 100644 --- a/Source/SwiftyJSON/SwiftyJSON.swift +++ b/Source/SwiftyJSON/SwiftyJSON.swift @@ -24,7 +24,7 @@ import Foundation // MARK: - Error // swiftlint:disable line_length -public enum SwiftyJSONError: Int, Swift.Error { +public enum SwiftyJSONError: Int, Swift.Error, Sendable { case unsupportedType = 999 case indexOutOfBounds = 900 case elementTooDeep = 902 @@ -67,7 +67,7 @@ JSON's type definitions. See http://www.json.org */ -public enum Type: Int { +public enum Type: Int, Sendable { case number case string case bool @@ -79,7 +79,7 @@ public enum Type: Int { // MARK: - JSON Base -public struct JSON { +public struct JSON: @unchecked Sendable { /** Creates a JSON using the data. @@ -339,7 +339,7 @@ extension JSON: Swift.Collection { /** * To mark both String and Int can be used in subscript. */ -public enum JSONKey { +public enum JSONKey: Sendable { case index(Int) case key(String) } diff --git a/Tests/SwiftJSONTests/ConcurrencyTests.swift b/Tests/SwiftJSONTests/ConcurrencyTests.swift new file mode 100644 index 00000000..bb51afde --- /dev/null +++ b/Tests/SwiftJSONTests/ConcurrencyTests.swift @@ -0,0 +1,386 @@ +// ConcurrencyTests.swift +// +// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import XCTest +import SwiftyJSON + +class ConcurrencyTests: XCTestCase { + + // MARK: - Test 1: Actor Boundary Passing + + actor DataProcessor { + func process(_ json: JSON) -> String { + return json["name"].stringValue + } + + func processDictionary(_ json: JSON) -> Int { + return json["count"].intValue + } + + func processArray(_ json: JSON) -> Int { + return json[0].intValue + } + } + + func testActorBoundaryPassing() async { + let json = JSON(["name": "Test"]) + let processor = DataProcessor() + let result = await processor.process(json) + XCTAssertEqual(result, "Test") + } + + func testActorBoundaryPassingWithDictionary() async { + let json = JSON(["count": 42, "status": "active"]) + let processor = DataProcessor() + let result = await processor.processDictionary(json) + XCTAssertEqual(result, 42) + } + + func testActorBoundaryPassingWithArray() async { + let json = JSON([100, 200, 300]) + let processor = DataProcessor() + let result = await processor.processArray(json) + XCTAssertEqual(result, 100) + } + + // MARK: - Test 2: Sendable Closure and Task + + func testSendableClosureWithTask() async { + let json = JSON(["value": "Hello"]) + let task = Task { @Sendable () -> String in + return json["value"].stringValue + } + let result = await task.value + XCTAssertEqual(result, "Hello") + } + + func testSendableClosureWithComplexData() async { + let json = JSON([ + "user": ["name": "Alice", "age": 30], + "active": true + ]) + let task = Task { @Sendable () -> String in + return json["user"]["name"].stringValue + } + let result = await task.value + XCTAssertEqual(result, "Alice") + } + + // MARK: - Test 3: Async JSON Parsing + + func testAsyncJSONParsing() async throws { + let jsonString = "{\"status\":\"ok\"}" + let data = jsonString.data(using: .utf8)! + + let task = Task { + return try JSON(data: data) + } + + let json = try await task.value + let status = json["status"].stringValue + XCTAssertEqual(status, "ok") + } + + func testAsyncJSONParsingWithComplexData() async throws { + let jsonString = "{\"results\": [{\"id\": 1, \"name\": \"Item1\"}, {\"id\": 2, \"name\": \"Item2\"}]}" + let data = jsonString.data(using: .utf8)! + + let task = Task { + return try JSON(data: data) + } + + let json = try await task.value + XCTAssertEqual(json["results"].arrayValue.count, 2) + XCTAssertEqual(json["results"][0]["name"].stringValue, "Item1") + } + + // MARK: - Test 4: Concurrent Read Access with TaskGroup + + func testConcurrentReadAccess() async { + let json = JSON(["values": [1, 2, 3, 4, 5]]) + + await withTaskGroup(of: Int.self) { group in + for i in 0..<5 { + group.addTask { + return json["values"][i].intValue + } + } + + var sum = 0 + for await value in group { + sum += value + } + XCTAssertEqual(sum, 15) + } + } + + func testConcurrentReadAccessWithDictionary() async { + let json = JSON([ + "items": [ + ["id": 1, "value": 10], + ["id": 2, "value": 20], + ["id": 3, "value": 30] + ] + ]) + + await withTaskGroup(of: Int.self) { group in + for i in 0..<3 { + group.addTask { + return json["items"][i]["value"].intValue + } + } + + var sum = 0 + for await value in group { + sum += value + } + XCTAssertEqual(sum, 60) + } + } + + // MARK: - Test 5: MainActor Isolation + + @MainActor + func mainActorFunction(_ json: JSON) -> String { + return json["title"].stringValue + } + + func testMainActorIsolation() async { + let json = JSON(["title": "Main Thread Task"]) + let result = await mainActorFunction(json) + XCTAssertEqual(result, "Main Thread Task") + } + + // MARK: - Test 6: Task.detached Isolation + + func testTaskDetachedIsolation() async { + let json = JSON(["data": "detached"]) + + let task = Task.detached { @Sendable () -> String in + return json["data"].stringValue + } + + let result = await task.value + XCTAssertEqual(result, "detached") + } + + // MARK: - Test 7: Complex Nested JSON + + func testComplexNestedJSONConcurrency() async { + let json = JSON([ + "users": [ + [ + "id": 1, + "name": "Alice", + "posts": [ + ["id": 101, "title": "Post 1"], + ["id": 102, "title": "Post 2"] + ] + ], + [ + "id": 2, + "name": "Bob", + "posts": [ + ["id": 201, "title": "Post 3"] + ] + ] + ] + ]) + + await withTaskGroup(of: (Int, String).self) { group in + for i in 0..<2 { + group.addTask { + let userId = json["users"][i]["id"].intValue + let userName = json["users"][i]["name"].stringValue + return (userId, userName) + } + } + + var names: [String] = [] + for await (_, name) in group { + names.append(name) + } + + XCTAssert(names.contains("Alice")) + XCTAssert(names.contains("Bob")) + } + } + + func testComplexNestedJSONAccess() async { + let json = JSON([ + [ + ["deep": [1, 2, 3]], + ["deep": [4, 5, 6]] + ], + [ + ["deep": [7, 8, 9]], + ["deep": [10, 11, 12]] + ] + ]) + + let task = Task { @Sendable () -> Int in + return json[0][1]["deep"][2].intValue + } + + let result = await task.value + XCTAssertEqual(result, 6) + } + + // MARK: - Test 8: All JSON Types in Concurrent Context + + func testAllJSONTypesInConcurrency() async { + let json = JSON([ + "string": "value", + "number": 42, + "bool": true, + "null": NSNull(), + "array": [1, 2, 3], + "dictionary": ["nested": "object"] + ]) + + await withTaskGroup(of: String.self) { group in + group.addTask { + return json["string"].stringValue + } + group.addTask { + return String(json["number"].intValue) + } + group.addTask { + return String(json["bool"].boolValue) + } + group.addTask { + return json["null"].type == .null ? "null" : "not_null" + } + group.addTask { + return String(json["array"].arrayValue.count) + } + group.addTask { + return json["dictionary"]["nested"].stringValue + } + + var results: [String] = [] + for await result in group { + results.append(result) + } + + XCTAssertEqual(results.count, 6) + XCTAssert(results.contains("value")) + XCTAssert(results.contains("42")) + XCTAssert(results.contains("true")) + XCTAssert(results.contains("null")) + XCTAssert(results.contains("3")) + XCTAssert(results.contains("object")) + } + } + + // MARK: - Test 9: Error Handling Across Actor Boundaries + + actor ErrorProcessor { + func processJSON(_ json: JSON) throws -> String { + guard json["required"].exists() else { + throw SwiftyJSONError.notExist + } + return json["required"].stringValue + } + + func processWithTypeError(_ json: JSON) throws -> Int { + guard json["count"].type == .number else { + throw SwiftyJSONError.wrongType + } + return json["count"].intValue + } + } + + func testErrorHandlingAcrossActorBoundaries() async { + let json = JSON(["other": "value"]) + let processor = ErrorProcessor() + + do { + _ = try await processor.processJSON(json) + XCTFail("Should have thrown notExist error") + } catch SwiftyJSONError.notExist { + // Expected behavior + } catch { + XCTFail("Unexpected error type: \(error)") + } + } + + func testErrorHandlingWithWrongType() async { + let json = JSON(["count": "not_a_number"]) + let processor = ErrorProcessor() + + do { + _ = try await processor.processWithTypeError(json) + XCTFail("Should have thrown wrongType error") + } catch SwiftyJSONError.wrongType { + // Expected behavior + } catch { + XCTFail("Unexpected error type: \(error)") + } + } + + func testSuccessfulErrorHandling() async { + let json = JSON(["required": "present", "count": 123]) + let processor = ErrorProcessor() + + do { + let result = try await processor.processJSON(json) + XCTAssertEqual(result, "present") + + let count = try await processor.processWithTypeError(json) + XCTAssertEqual(count, 123) + } catch { + XCTFail("Should not have thrown error: \(error)") + } + } + + // MARK: - Test 10: Mixed Async Operations + + func testMixedAsyncOperations() async throws { + let jsonString = "{\"users\": [{\"id\": 1, \"name\": \"User1\"}, {\"id\": 2, \"name\": \"User2\"}]}" + let data = jsonString.data(using: .utf8)! + + let parseTask = Task { + return try JSON(data: data) + } + + let json = try await parseTask.value + + let names = await withTaskGroup(of: String.self) { group in + for i in 0..<2 { + group.addTask { + return json["users"][i]["name"].stringValue + } + } + + var result: [String] = [] + for await name in group { + result.append(name) + } + return result + } + + XCTAssertEqual(names.count, 2) + XCTAssert(names.contains("User1")) + XCTAssert(names.contains("User2")) + } +} From 636b70007f3ea3fe57df40151faaf1d62042fdaf Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 26 Jan 2026 17:27:31 -0700 Subject: [PATCH 257/260] Consolidate concurrency tests to 3 focused tests Each test now directly corresponds to a type made Sendable: - testJSONSendable: JSON crosses actor boundary - testTypeSendable: Type enum crosses actor boundary - testSwiftyJSONErrorSendable: SwiftyJSONError crosses actor boundary Removed redundant tests that proved the same thing in different ways (TaskGroup, Task.detached, MainActor variations). Added missing coverage for Type enum Sendable conformance. --- Tests/SwiftJSONTests/ConcurrencyTests.swift | 375 ++------------------ 1 file changed, 39 insertions(+), 336 deletions(-) diff --git a/Tests/SwiftJSONTests/ConcurrencyTests.swift b/Tests/SwiftJSONTests/ConcurrencyTests.swift index bb51afde..a6eaa099 100644 --- a/Tests/SwiftJSONTests/ConcurrencyTests.swift +++ b/Tests/SwiftJSONTests/ConcurrencyTests.swift @@ -23,364 +23,67 @@ import XCTest import SwiftyJSON +/// Tests verifying Sendable conformance for Swift 6 concurrency. +/// Each test targets a specific type made Sendable in this PR. class ConcurrencyTests: XCTestCase { - // MARK: - Test 1: Actor Boundary Passing - - actor DataProcessor { - func process(_ json: JSON) -> String { - return json["name"].stringValue - } - - func processDictionary(_ json: JSON) -> Int { - return json["count"].intValue - } - - func processArray(_ json: JSON) -> Int { - return json[0].intValue - } - } - - func testActorBoundaryPassing() async { - let json = JSON(["name": "Test"]) - let processor = DataProcessor() - let result = await processor.process(json) - XCTAssertEqual(result, "Test") - } - - func testActorBoundaryPassingWithDictionary() async { - let json = JSON(["count": 42, "status": "active"]) - let processor = DataProcessor() - let result = await processor.processDictionary(json) - XCTAssertEqual(result, 42) - } - - func testActorBoundaryPassingWithArray() async { - let json = JSON([100, 200, 300]) - let processor = DataProcessor() - let result = await processor.processArray(json) - XCTAssertEqual(result, 100) - } - - // MARK: - Test 2: Sendable Closure and Task - - func testSendableClosureWithTask() async { - let json = JSON(["value": "Hello"]) - let task = Task { @Sendable () -> String in - return json["value"].stringValue - } - let result = await task.value - XCTAssertEqual(result, "Hello") - } - - func testSendableClosureWithComplexData() async { - let json = JSON([ - "user": ["name": "Alice", "age": 30], - "active": true - ]) - let task = Task { @Sendable () -> String in - return json["user"]["name"].stringValue - } - let result = await task.value - XCTAssertEqual(result, "Alice") - } - - // MARK: - Test 3: Async JSON Parsing - - func testAsyncJSONParsing() async throws { - let jsonString = "{\"status\":\"ok\"}" - let data = jsonString.data(using: .utf8)! - - let task = Task { - return try JSON(data: data) + actor Processor { + func extract(_ json: JSON) -> String { + json["name"].stringValue } - let json = try await task.value - let status = json["status"].stringValue - XCTAssertEqual(status, "ok") - } - - func testAsyncJSONParsingWithComplexData() async throws { - let jsonString = "{\"results\": [{\"id\": 1, \"name\": \"Item1\"}, {\"id\": 2, \"name\": \"Item2\"}]}" - let data = jsonString.data(using: .utf8)! - - let task = Task { - return try JSON(data: data) + func extractType(_ json: JSON) -> Type { + json["value"].type } - let json = try await task.value - XCTAssertEqual(json["results"].arrayValue.count, 2) - XCTAssertEqual(json["results"][0]["name"].stringValue, "Item1") - } - - // MARK: - Test 4: Concurrent Read Access with TaskGroup - - func testConcurrentReadAccess() async { - let json = JSON(["values": [1, 2, 3, 4, 5]]) - - await withTaskGroup(of: Int.self) { group in - for i in 0..<5 { - group.addTask { - return json["values"][i].intValue - } - } - - var sum = 0 - for await value in group { - sum += value - } - XCTAssertEqual(sum, 15) - } - } - - func testConcurrentReadAccessWithDictionary() async { - let json = JSON([ - "items": [ - ["id": 1, "value": 10], - ["id": 2, "value": 20], - ["id": 3, "value": 30] - ] - ]) - - await withTaskGroup(of: Int.self) { group in - for i in 0..<3 { - group.addTask { - return json["items"][i]["value"].intValue - } - } - - var sum = 0 - for await value in group { - sum += value - } - XCTAssertEqual(sum, 60) - } - } - - // MARK: - Test 5: MainActor Isolation - - @MainActor - func mainActorFunction(_ json: JSON) -> String { - return json["title"].stringValue - } - - func testMainActorIsolation() async { - let json = JSON(["title": "Main Thread Task"]) - let result = await mainActorFunction(json) - XCTAssertEqual(result, "Main Thread Task") - } - - // MARK: - Test 6: Task.detached Isolation - - func testTaskDetachedIsolation() async { - let json = JSON(["data": "detached"]) - - let task = Task.detached { @Sendable () -> String in - return json["data"].stringValue - } - - let result = await task.value - XCTAssertEqual(result, "detached") - } - - // MARK: - Test 7: Complex Nested JSON - - func testComplexNestedJSONConcurrency() async { - let json = JSON([ - "users": [ - [ - "id": 1, - "name": "Alice", - "posts": [ - ["id": 101, "title": "Post 1"], - ["id": 102, "title": "Post 2"] - ] - ], - [ - "id": 2, - "name": "Bob", - "posts": [ - ["id": 201, "title": "Post 3"] - ] - ] - ] - ]) - - await withTaskGroup(of: (Int, String).self) { group in - for i in 0..<2 { - group.addTask { - let userId = json["users"][i]["id"].intValue - let userName = json["users"][i]["name"].stringValue - return (userId, userName) - } - } - - var names: [String] = [] - for await (_, name) in group { - names.append(name) - } - - XCTAssert(names.contains("Alice")) - XCTAssert(names.contains("Bob")) - } - } - - func testComplexNestedJSONAccess() async { - let json = JSON([ - [ - ["deep": [1, 2, 3]], - ["deep": [4, 5, 6]] - ], - [ - ["deep": [7, 8, 9]], - ["deep": [10, 11, 12]] - ] - ]) - - let task = Task { @Sendable () -> Int in - return json[0][1]["deep"][2].intValue - } - - let result = await task.value - XCTAssertEqual(result, 6) - } - - // MARK: - Test 8: All JSON Types in Concurrent Context - - func testAllJSONTypesInConcurrency() async { - let json = JSON([ - "string": "value", - "number": 42, - "bool": true, - "null": NSNull(), - "array": [1, 2, 3], - "dictionary": ["nested": "object"] - ]) - - await withTaskGroup(of: String.self) { group in - group.addTask { - return json["string"].stringValue - } - group.addTask { - return String(json["number"].intValue) - } - group.addTask { - return String(json["bool"].boolValue) - } - group.addTask { - return json["null"].type == .null ? "null" : "not_null" - } - group.addTask { - return String(json["array"].arrayValue.count) - } - group.addTask { - return json["dictionary"]["nested"].stringValue - } - - var results: [String] = [] - for await result in group { - results.append(result) - } - - XCTAssertEqual(results.count, 6) - XCTAssert(results.contains("value")) - XCTAssert(results.contains("42")) - XCTAssert(results.contains("true")) - XCTAssert(results.contains("null")) - XCTAssert(results.contains("3")) - XCTAssert(results.contains("object")) - } - } - - // MARK: - Test 9: Error Handling Across Actor Boundaries - - actor ErrorProcessor { - func processJSON(_ json: JSON) throws -> String { + func requireField(_ json: JSON) throws -> String { guard json["required"].exists() else { throw SwiftyJSONError.notExist } return json["required"].stringValue } - - func processWithTypeError(_ json: JSON) throws -> Int { - guard json["count"].type == .number else { - throw SwiftyJSONError.wrongType - } - return json["count"].intValue - } } - func testErrorHandlingAcrossActorBoundaries() async { - let json = JSON(["other": "value"]) - let processor = ErrorProcessor() - - do { - _ = try await processor.processJSON(json) - XCTFail("Should have thrown notExist error") - } catch SwiftyJSONError.notExist { - // Expected behavior - } catch { - XCTFail("Unexpected error type: \(error)") - } - } + /// Verifies JSON conforms to Sendable (can cross actor boundary) + func testJSONSendable() async { + let json = JSON(["name": "test", "count": 42]) + let processor = Processor() - func testErrorHandlingWithWrongType() async { - let json = JSON(["count": "not_a_number"]) - let processor = ErrorProcessor() + let result = await processor.extract(json) - do { - _ = try await processor.processWithTypeError(json) - XCTFail("Should have thrown wrongType error") - } catch SwiftyJSONError.wrongType { - // Expected behavior - } catch { - XCTFail("Unexpected error type: \(error)") - } + XCTAssertEqual(result, "test") } - func testSuccessfulErrorHandling() async { - let json = JSON(["required": "present", "count": 123]) - let processor = ErrorProcessor() + /// Verifies Type enum conforms to Sendable (can be returned across actor boundary) + func testTypeSendable() async { + let processor = Processor() - do { - let result = try await processor.processJSON(json) - XCTAssertEqual(result, "present") + let stringType = await processor.extractType(JSON(["value": "hello"])) + let numberType = await processor.extractType(JSON(["value": 123])) + let boolType = await processor.extractType(JSON(["value": true])) + let nullType = await processor.extractType(JSON(["value": NSNull()])) + let arrayType = await processor.extractType(JSON(["value": [1, 2, 3]])) + let dictType = await processor.extractType(JSON(["value": ["nested": "object"]])) - let count = try await processor.processWithTypeError(json) - XCTAssertEqual(count, 123) - } catch { - XCTFail("Should not have thrown error: \(error)") - } + XCTAssertEqual(stringType, .string) + XCTAssertEqual(numberType, .number) + XCTAssertEqual(boolType, .bool) + XCTAssertEqual(nullType, .null) + XCTAssertEqual(arrayType, .array) + XCTAssertEqual(dictType, .dictionary) } - // MARK: - Test 10: Mixed Async Operations + /// Verifies SwiftyJSONError conforms to Sendable (can be thrown across actor boundary) + func testSwiftyJSONErrorSendable() async { + let processor = Processor() - func testMixedAsyncOperations() async throws { - let jsonString = "{\"users\": [{\"id\": 1, \"name\": \"User1\"}, {\"id\": 2, \"name\": \"User2\"}]}" - let data = jsonString.data(using: .utf8)! - - let parseTask = Task { - return try JSON(data: data) - } - - let json = try await parseTask.value - - let names = await withTaskGroup(of: String.self) { group in - for i in 0..<2 { - group.addTask { - return json["users"][i]["name"].stringValue - } - } - - var result: [String] = [] - for await name in group { - result.append(name) - } - return result + do { + _ = try await processor.requireField(JSON(["other": "value"])) + XCTFail("Should have thrown") + } catch SwiftyJSONError.notExist { + // Error successfully crossed actor boundary + } catch { + XCTFail("Unexpected error: \(error)") } - - XCTAssertEqual(names.count, 2) - XCTAssert(names.contains("User1")) - XCTAssert(names.contains("User2")) } } From d24f061e37c6e0f40b99a53846e9d4682fe01d57 Mon Sep 17 00:00:00 2001 From: wongzigii Date: Wed, 4 Feb 2026 17:10:27 +0800 Subject: [PATCH 258/260] update ci --- .github/workflows/ci.yml | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2680e910..a3816d45 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,14 +12,12 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v4 - - - name: Set up Swift - uses: swift-actions/setup-swift@v2 - with: - swift-version: '6.0' + + - name: Select Xcode + run: sudo xcode-select -s /Applications/Xcode_16.4.app - name: Build - run: swift build --build-tests + run: xcrun swift build --build-tests - name: Run tests - run: swift test \ No newline at end of file + run: xcrun swift test \ No newline at end of file From 28094b0b74ea2c26003dee4d2b916a3943027ef5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?jean=2E333=28=E1=84=8C=E1=85=A5=E1=86=BC=E1=84=8B=E1=85=B2?= =?UTF-8?q?=E1=84=8C=E1=85=B5=E1=86=AB=29/kakaomobility?= <41438361+Yoojin99@users.noreply.github.com> Date: Thu, 26 Feb 2026 15:14:18 +0900 Subject: [PATCH 259/260] Fix Tests group path in Xcode project --- SwiftyJSON.xcodeproj/project.pbxproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftyJSON.xcodeproj/project.pbxproj b/SwiftyJSON.xcodeproj/project.pbxproj index ec223336..3c325ac2 100644 --- a/SwiftyJSON.xcodeproj/project.pbxproj +++ b/SwiftyJSON.xcodeproj/project.pbxproj @@ -278,7 +278,7 @@ 2E4FEFEB19575BE100351305 /* Supporting Files */, ); name = Tests; - path = Tests/Tes; + path = Tests/SwiftJSONTests; sourceTree = ""; }; 2E4FEFEB19575BE100351305 /* Supporting Files */ = { From d9712989ba2275f2d04e62a9fa74e704bc54fdda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?jean=2E333=28=E1=84=8C=E1=85=A5=E1=86=BC=E1=84=8B=E1=85=B2?= =?UTF-8?q?=E1=84=8C=E1=85=B5=E1=86=AB=29/kakaomobility?= <41438361+Yoojin99@users.noreply.github.com> Date: Thu, 26 Feb 2026 16:06:37 +0900 Subject: [PATCH 260/260] Fix test resource loading for Xcode and SwiftPM --- Tests/SwiftJSONTests/BaseTests.swift | 9 ++++++--- Tests/SwiftJSONTests/PerformanceTests.swift | 7 ++++++- Tests/SwiftJSONTests/SequenceTypeTests.swift | 7 ++++++- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/Tests/SwiftJSONTests/BaseTests.swift b/Tests/SwiftJSONTests/BaseTests.swift index 634e1c8b..8bbebcde 100644 --- a/Tests/SwiftJSONTests/BaseTests.swift +++ b/Tests/SwiftJSONTests/BaseTests.swift @@ -31,9 +31,12 @@ class BaseTests: XCTestCase { super.setUp() -// let file = "./Tests/Tes/Tests.json" -// self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) - if let file = Bundle.module.url(forResource: "Tests", withExtension: "json") { + #if SWIFT_PACKAGE + let testBundle = Bundle.module + #else + let testBundle = Bundle(for: BaseTests.self) + #endif + if let file = testBundle.url(forResource: "Tests", withExtension: "json") { self.testData = try? Data(contentsOf: file) } else { XCTFail("Can't find the test JSON file") diff --git a/Tests/SwiftJSONTests/PerformanceTests.swift b/Tests/SwiftJSONTests/PerformanceTests.swift index 70f1f2f2..c0e6cc0b 100644 --- a/Tests/SwiftJSONTests/PerformanceTests.swift +++ b/Tests/SwiftJSONTests/PerformanceTests.swift @@ -30,7 +30,12 @@ class PerformanceTests: XCTestCase { override func setUp() { super.setUp() - if let file = Bundle.module.url(forResource: "Tests", withExtension: "json") { + #if SWIFT_PACKAGE + let testBundle = Bundle.module + #else + let testBundle = Bundle(for: PerformanceTests.self) + #endif + if let file = testBundle.url(forResource: "Tests", withExtension: "json") { self.testData = try? Data(contentsOf: file) } else { XCTFail("Can't find the test JSON file") diff --git a/Tests/SwiftJSONTests/SequenceTypeTests.swift b/Tests/SwiftJSONTests/SequenceTypeTests.swift index 557c3dbb..a039453f 100644 --- a/Tests/SwiftJSONTests/SequenceTypeTests.swift +++ b/Tests/SwiftJSONTests/SequenceTypeTests.swift @@ -28,7 +28,12 @@ class SequenceTypeTests: XCTestCase { var testData: Data? func testJSONFile() { - if let file = Bundle.module.url(forResource: "Tests", withExtension: "json") { + #if SWIFT_PACKAGE + let testBundle = Bundle.module + #else + let testBundle = Bundle(for: SequenceTypeTests.self) + #endif + if let file = testBundle.url(forResource: "Tests", withExtension: "json") { self.testData = try? Data(contentsOf: file) guard let json = try? JSON(data: self.testData!) else { XCTFail("Unable to parse the data")