Skip to content

Commit e1ce485

Browse files
committed
Merge branch 'master' of https://github.com/SwiftyJSON/SwiftyJSON into swiftlint
* 'master' of https://github.com/SwiftyJSON/SwiftyJSON: [Tests] Improve SwiftyJSON Mutability test cases Fix a spelling mistake and simplify initialize methods invoking Fix a spelling mistake and merge duplicate test files rawValue test fix nested JSON problems with JSON initialize method # Conflicts: # Source/SwiftyJSON.swift
2 parents 024efa4 + 007cb9f commit e1ce485

File tree

4 files changed

+172
-73
lines changed

4 files changed

+172
-73
lines changed

Source/SwiftyJSON.swift

+26-73
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,6 @@ public struct JSON {
8484
*/
8585
public init(_ object: Any) {
8686
switch object {
87-
case let object as [JSON] where object.count > 0:
88-
self.init(array: object)
89-
case let object as [String: JSON] where object.count > 0:
90-
self.init(dictionary: object)
9187
case let object as Data:
9288
self.init(data: object)
9389
default:
@@ -131,33 +127,6 @@ public struct JSON {
131127
self.object = jsonObject
132128
}
133129

134-
/**
135-
Creates a JSON from a [JSON]
136-
137-
- parameter jsonArray: A Swift array of JSON objects
138-
139-
- returns: The created JSON
140-
*/
141-
fileprivate init(array: [JSON]) {
142-
self.init(array.map { $0.object })
143-
}
144-
145-
/**
146-
Creates a JSON from a [String: JSON]
147-
148-
- parameter jsonDictionary: A Swift dictionary of JSON objects
149-
150-
- returns: The created JSON
151-
*/
152-
fileprivate init(dictionary: [String: JSON]) {
153-
var newDictionary = [String: Any](minimumCapacity: dictionary.count)
154-
for (key, json) in dictionary {
155-
newDictionary[key] = json.object
156-
}
157-
158-
self.init(newDictionary)
159-
}
160-
161130
/**
162131
Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added,
163132
present values getting overwritten, array values getting appended and nested JSONs getting merged the same way.
@@ -238,7 +207,7 @@ public struct JSON {
238207
}
239208
set {
240209
_error = nil
241-
switch newValue {
210+
switch unwrap(newValue) {
242211
case let number as NSNumber:
243212
if number.isBool {
244213
_type = .bool
@@ -252,10 +221,8 @@ public struct JSON {
252221
self.rawString = string
253222
case _ as NSNull:
254223
_type = .null
255-
case _ as [JSON]:
256-
_type = .array
257-
case nil:
258-
_type = .null
224+
case nil:
225+
_type = .null
259226
case let array as [Any]:
260227
_type = .array
261228
self.rawArray = array
@@ -281,6 +248,24 @@ public struct JSON {
281248
public static var null: JSON { return JSON(NSNull()) }
282249
}
283250

251+
// unwrap nested JSON
252+
private func unwrap(_ object: Any) -> Any {
253+
switch object {
254+
case let json as JSON:
255+
return unwrap(json.object)
256+
case let array as [Any]:
257+
return array.map(unwrap)
258+
case let dictionary as [String : Any]:
259+
var unwrappedDic = dictionary
260+
for (k, v) in dictionary {
261+
unwrappedDic[k] = unwrap(v)
262+
}
263+
return unwrappedDic
264+
default:
265+
return object
266+
}
267+
}
268+
284269
public enum Index<T: Any>: Comparable {
285270
case array(Int)
286271
case dictionary(DictionaryIndex<String, T>)
@@ -313,7 +298,7 @@ public enum Index<T: Any>: Comparable {
313298
public typealias JSONIndex = Index<JSON>
314299
public typealias JSONRawIndex = Index<Any>
315300

316-
extension JSON: Collection {
301+
extension JSON: Swift.Collection {
317302

318303
public typealias Index = JSONRawIndex
319304

@@ -348,7 +333,6 @@ extension JSON: Collection {
348333
default:
349334
return .null
350335
}
351-
352336
}
353337

354338
public subscript (position: Index) -> (String, JSON) {
@@ -362,7 +346,6 @@ extension JSON: Collection {
362346
return ("", JSON.null)
363347
}
364348
}
365-
366349
}
367350

368351
// MARK: - Subscript
@@ -548,41 +531,11 @@ extension JSON: Swift.ExpressibleByFloatLiteral {
548531

549532
extension JSON: Swift.ExpressibleByDictionaryLiteral {
550533
public init(dictionaryLiteral elements: (String, Any)...) {
551-
let array = elements
552-
self.init(dictionaryLiteral: array)
553-
}
554-
555-
public init(dictionaryLiteral elements: [(String, Any)]) {
556-
let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in
557-
let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in
558-
if let value = dictionary[key] {
559-
return (key, value)
560-
}
561-
return nil
562-
}
563-
return JSON(dictionaryLiteral: initializeElement)
564-
}
565-
566-
var dict = [String: Any](minimumCapacity: elements.count)
567-
568-
for element in elements {
569-
let elementToSet: Any
570-
if let json = element.1 as? JSON {
571-
elementToSet = json.object
572-
} else if let jsonArray = element.1 as? [JSON] {
573-
elementToSet = JSON(jsonArray).object
574-
} else if let dictionary = element.1 as? [String : Any] {
575-
elementToSet = jsonFromDictionaryLiteral(dictionary).object
576-
} else if let dictArray = element.1 as? [[String : Any]] {
577-
let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) }
578-
elementToSet = JSON(jsonArray).object
579-
} else {
580-
elementToSet = element.1
581-
}
582-
dict[element.0] = elementToSet
534+
var dictionary = [String : Any](minimumCapacity: elements.count)
535+
for (k, v) in elements {
536+
dictionary[k] = v
583537
}
584-
585-
self.init(dict)
538+
self.init(dictionary as Any)
586539
}
587540
}
588541

SwiftyJSON.xcodeproj/project.pbxproj

+8
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@
5353
A819C49F19E2EE5B00ADCC3D /* SubscriptTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */; };
5454
A819C4A119E37FC600ADCC3D /* PrintableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A819C4A019E37FC600ADCC3D /* PrintableTests.swift */; };
5555
A81CBA0B1BCF6B0200A649A2 /* Tests.json in Resources */ = {isa = PBXBuildFile; fileRef = A885D1DA19CFCFF0002FD4C3 /* Tests.json */; };
56+
A830A6951E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */; };
57+
A830A6961E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */; };
58+
A830A6971E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */; };
5659
A8491E1E19CD6DAE00CCFAE6 /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8491E1D19CD6DAE00CCFAE6 /* SwiftyJSON.swift */; };
5760
A8580F791BCF5C5B00DA927B /* SwiftyJSON.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7236B4F61BAC14150020529B /* SwiftyJSON.framework */; };
5861
A8580F801BCF69A000DA927B /* PerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A86BAA0D19EBC32B009EAAEB /* PerformanceTests.swift */; };
@@ -124,6 +127,7 @@
124127
A819C49E19E2EE5B00ADCC3D /* SubscriptTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SubscriptTests.swift; sourceTree = "<group>"; };
125128
A819C4A019E37FC600ADCC3D /* PrintableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrintableTests.swift; sourceTree = "<group>"; };
126129
A82A1C0D19D922DC009A653D /* Info-iOS.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = "<group>"; };
130+
A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutabilityTests.swift; sourceTree = "<group>"; };
127131
A8491E1D19CD6DAE00CCFAE6 /* SwiftyJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftyJSON.swift; sourceTree = "<group>"; };
128132
A8580F741BCF5C5B00DA927B /* SwiftyJSON tvOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SwiftyJSON tvOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
129133
A8580F781BCF5C5B00DA927B /* Info-tvOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-tvOS.plist"; sourceTree = "<group>"; };
@@ -259,6 +263,7 @@
259263
A87080E719E439DA00CDE086 /* NumberTests.swift */,
260264
A863BE2719EED46F0092A41F /* RawTests.swift */,
261265
A8B66C8B19E51D6500540692 /* DictionaryTests.swift */,
266+
A830A6941E5B2DD8001D7F6D /* MutabilityTests.swift */,
262267
A8B66C8D19E52F4200540692 /* ArrayTests.swift */,
263268
2E4FEFEB19575BE100351305 /* Supporting Files */,
264269
);
@@ -597,6 +602,7 @@
597602
A86BAA0E19EBC32B009EAAEB /* PerformanceTests.swift in Sources */,
598603
A819C49919E1B10300ADCC3D /* RawRepresentableTests.swift in Sources */,
599604
A819C49F19E2EE5B00ADCC3D /* SubscriptTests.swift in Sources */,
605+
A830A6951E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */,
600606
A863BE2819EED46F0092A41F /* RawTests.swift in Sources */,
601607
A885D1D219CF1EE6002FD4C3 /* BaseTests.swift in Sources */,
602608
A8B66C8E19E52F4200540692 /* ArrayTests.swift in Sources */,
@@ -635,6 +641,7 @@
635641
9C459F021A9103C1008C9A41 /* NumberTests.swift in Sources */,
636642
9C459EFF1A9103C1008C9A41 /* RawRepresentableTests.swift in Sources */,
637643
9C459EFA1A9103C1008C9A41 /* BaseTests.swift in Sources */,
644+
A830A6961E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */,
638645
9C459F041A9103C1008C9A41 /* DictionaryTests.swift in Sources */,
639646
9C459EF91A9103C1008C9A41 /* PerformanceTests.swift in Sources */,
640647
9C459EFE1A9103C1008C9A41 /* LiteralConvertibleTests.swift in Sources */,
@@ -657,6 +664,7 @@
657664
A8580F821BCF69A000DA927B /* SequenceTypeTests.swift in Sources */,
658665
A8580F831BCF69A000DA927B /* PrintableTests.swift in Sources */,
659666
A8580F841BCF69A000DA927B /* SubscriptTests.swift in Sources */,
667+
A830A6971E5B2DD8001D7F6D /* MutabilityTests.swift in Sources */,
660668
A8580F851BCF69A000DA927B /* LiteralConvertibleTests.swift in Sources */,
661669
A8580F861BCF69A000DA927B /* RawRepresentableTests.swift in Sources */,
662670
A8580F871BCF69A000DA927B /* ComparableTests.swift in Sources */,
+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// DictionaryTests.swift
2+
//
3+
// Copyright (c) 2014 - 2017 Zigii Wong
4+
//
5+
// Permission is hereby granted, free of charge, to any person obtaining a copy
6+
// of this software and associated documentation files (the "Software"), to deal
7+
// in the Software without restriction, including without limitation the rights
8+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
// copies of the Software, and to permit persons to whom the Software is
10+
// furnished to do so, subject to the following conditions:
11+
//
12+
// The above copyright notice and this permission notice shall be included in
13+
// all copies or substantial portions of the Software.
14+
//
15+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
// THE SOFTWARE.
22+
23+
import XCTest
24+
import SwiftyJSON
25+
26+
class MutabilityTest: XCTestCase {
27+
28+
func testDictionaryJSONMutability() {
29+
let dictionary: [String: Any] = [
30+
"string": "STRING",
31+
"number": 9823.212,
32+
"bool": true,
33+
"empty": ["nothing"]
34+
]
35+
36+
var json = JSON(dictionary)
37+
XCTAssertEqual(json["string"], "STRING")
38+
XCTAssertEqual(json["number"], 9823.212)
39+
XCTAssertEqual(json["bool"], true)
40+
XCTAssertEqual(json["empty"], ["nothing"])
41+
42+
json["string"] = "muted"
43+
XCTAssertEqual(json["string"], "muted")
44+
45+
json["number"] = 9999.0
46+
XCTAssertEqual(json["number"], 9999.0)
47+
48+
json["bool"] = false
49+
XCTAssertEqual(json["bool"], false)
50+
51+
json["empty"] = []
52+
XCTAssertEqual(json["empty"], [])
53+
54+
json["new"] = JSON(["foo": "bar"])
55+
XCTAssertEqual(json["new"], ["foo": "bar"])
56+
}
57+
58+
func testArrayJSONMutability() {
59+
let array: [Any] = ["1", "2", 3, true, []]
60+
61+
var json = JSON(array)
62+
XCTAssertEqual(json[0], "1")
63+
XCTAssertEqual(json[1], "2")
64+
XCTAssertEqual(json[2], 3)
65+
XCTAssertEqual(json[3], true)
66+
XCTAssertEqual(json[4], [])
67+
68+
json[0] = false
69+
XCTAssertEqual(json[0], false)
70+
71+
json[1] = 2
72+
XCTAssertEqual(json[1], 2)
73+
74+
json[2] = "3"
75+
XCTAssertEqual(json[2], "3")
76+
77+
json[3] = [:]
78+
XCTAssertEqual(json[3], [:])
79+
80+
json[4] = [1, 2]
81+
XCTAssertEqual(json[4], [1, 2])
82+
}
83+
84+
func testValueMutability() {
85+
var intArray = JSON([0, 1, 2])
86+
intArray[0] = JSON(55)
87+
XCTAssertEqual(intArray[0], 55)
88+
XCTAssertEqual(intArray[0].intValue, 55)
89+
90+
var dictionary = JSON(["foo": "bar"])
91+
dictionary["foo"] = JSON("foo")
92+
XCTAssertEqual(dictionary["foo"], "foo")
93+
XCTAssertEqual(dictionary["foo"].stringValue, "foo")
94+
95+
var number = JSON(1)
96+
number = JSON("111")
97+
XCTAssertEqual(number, "111")
98+
XCTAssertEqual(number.intValue, 111)
99+
XCTAssertEqual(number.stringValue, "111")
100+
101+
var boolean = JSON(true)
102+
boolean = JSON(false)
103+
XCTAssertEqual(boolean, false)
104+
XCTAssertEqual(boolean.boolValue, false)
105+
}
106+
}

Tests/SwiftyJSONTests/NestedJSONTests.swift

+32
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,36 @@ class NestedJSONTests: XCTestCase {
3939
]
4040
XCTAssertNotNil(try? nestedFamily.rawData())
4141
}
42+
43+
func testArrayJSON() {
44+
let arr: [JSON] = ["a", 1, ["b", 2]]
45+
let json = JSON(arr)
46+
XCTAssertEqual(json[0].string, "a")
47+
XCTAssertEqual(json[2,1].int, 2)
48+
}
49+
50+
func testDictionaryJSON() {
51+
let json: JSON = ["a": JSON("1"), "b": JSON([1, 2, "3"]), "c": JSON(["aa": "11", "bb": 22])]
52+
XCTAssertEqual(json["a"].string, "1")
53+
XCTAssertEqual(json["b"].array!, [1, 2, "3"])
54+
XCTAssertEqual(json["c"]["aa"].string, "11")
55+
}
56+
57+
func testNestedJSON() {
58+
let inner = JSON([
59+
"some_field": "1" + "2",
60+
])
61+
let json = JSON([
62+
"outer_field": "1" + "2",
63+
"inner_json": inner
64+
])
65+
XCTAssertEqual(json["inner_json"], ["some_field": "12"])
66+
67+
let foo = "foo"
68+
let json2 = JSON([
69+
"outer_field": foo,
70+
"inner_json": inner
71+
])
72+
XCTAssertEqual(json2["inner_json"].rawValue as! [String : String], ["some_field": "12"])
73+
}
4274
}

0 commit comments

Comments
 (0)