From b311c581af557425db1cebfba2654c3b8b79ceea Mon Sep 17 00:00:00 2001 From: Jeff Kang Date: Fri, 16 Dec 2016 14:12:03 +0900 Subject: [PATCH 001/134] 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 29a064b923b1199625b22334c4bc5f030bc85c25 Mon Sep 17 00:00:00 2001 From: "Robert M. Ryan" Date: Sun, 1 Jan 2017 21:33:57 -0800 Subject: [PATCH 002/134] 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 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 003/134] 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 004/134] 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 005/134] [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 006/134] 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 007/134] 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 008/134] [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 009/134] [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 010/134] [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 011/134] 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 012/134] [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 013/134] [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 014/134] [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 015/134] [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 016/134] 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 017/134] 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 018/134] 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 019/134] [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 020/134] 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 021/134] 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 022/134] 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 023/134] [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 024/134] [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 025/134] 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 026/134] 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 027/134] 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 028/134] 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 029/134] 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 030/134] 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 031/134] =?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 032/134] 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 033/134] 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 034/134] =?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 035/134] =?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 036/134] 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 037/134] [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 038/134] 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 039/134] [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 040/134] [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 041/134] [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 042/134] 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 043/134] 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 044/134] 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 045/134] 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 046/134] 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 047/134] 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 048/134] 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 049/134] [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 050/134] [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 051/134] [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 052/134] [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 053/134] [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 054/134] 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 055/134] 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 056/134] 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 057/134] 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 058/134] 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 059/134] [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 060/134] 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 061/134] 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 062/134] 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 063/134] 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 064/134] 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 065/134] 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 066/134] 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 067/134] 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 068/134] 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 069/134] 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 070/134] 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 071/134] 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 072/134] 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 073/134] 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 074/134] 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 075/134] 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 076/134] 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 077/134] 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 078/134] 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 079/134] 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 080/134] 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 081/134] 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 082/134] 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 083/134] 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 084/134] 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 085/134] 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 086/134] 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 087/134] 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 088/134] 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 089/134] 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 090/134] 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 091/134] 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 092/134] 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 093/134] 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 094/134] 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 095/134] 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 096/134] 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 097/134] 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 098/134] 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 099/134] 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 100/134] 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 101/134] 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 102/134] 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 103/134] 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 104/134] 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 105/134] 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 106/134] 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 107/134] 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 108/134] 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 109/134] 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 110/134] 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 111/134] 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 112/134] 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 113/134] 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 114/134] 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 115/134] 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 116/134] 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 117/134] 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 118/134] 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 119/134] 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 120/134] 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 121/134] 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 122/134] 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 123/134] 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 124/134] 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 125/134] 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 126/134] 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 127/134] 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 128/134] 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 129/134] 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 130/134] 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 131/134] 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 132/134] 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") From 7eaf81fac49c7215cacd25ad58a3875745507c5b Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 18 Aug 2026 07:02:01 +0000 Subject: [PATCH 133/134] Initial plan From dd217c552b351fde032e5d5b5aecd0c68f9b077b Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 18 Aug 2026 07:02:56 +0000 Subject: [PATCH 134/134] Fix CI: remove hardcoded Xcode 16.4 path that doesn't exist on runner Co-authored-by: wongzigii <7384288+wongzigii@users.noreply.github.com> --- .github/workflows/ci.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a3816d45..ba72e725 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,9 +13,6 @@ jobs: - name: Checkout code uses: actions/checkout@v4 - - name: Select Xcode - run: sudo xcode-select -s /Applications/Xcode_16.4.app - - name: Build run: xcrun swift build --build-tests