Skip to content

Commit d32f7e3

Browse files
committed
Merge pull request #9 from kreeger/feature/clearer-null-nil-checks
Add check for null value using hasValue; rename isNil to hasKey.
2 parents 1978ec9 + 5078697 commit d32f7e3

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

ModelRocket/JSON.swift

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,17 @@ public struct JSON {
7070
}
7171
}
7272

73-
public var isNil: Bool {
73+
@available(*, deprecated=1.2, message="Use !hasKey instead.") public var isNil: Bool {
7474
return (object == nil)
7575
}
76+
77+
public var hasKey: Bool {
78+
return object != nil
79+
}
80+
81+
public var hasValue: Bool {
82+
return object != nil && !(object is NSNull)
83+
}
7684
}
7785

7886
// MARK: - CustomStringConvertible

ModelRocketTests/JSONTests.swift

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@ class JSONTests: XCTestCase {
5555

5656
// No data
5757
let emptyJSON = JSON(data: nil)
58-
XCTAssertTrue(emptyJSON.isNil, "JSON not nil")
58+
XCTAssertFalse(emptyJSON.hasKey, "JSON is not nil")
59+
XCTAssertFalse(emptyJSON.hasValue, "JSON has a value")
5960

6061
// String
6162
XCTAssertEqual(vehicleJSON["make"].stringValue, "BMW")
@@ -436,6 +437,16 @@ class JSONTests: XCTestCase {
436437
XCTAssertEqual(json["array"][0].intValue, 1)
437438
}
438439

440+
// MARK: - NSNull (from loaded data)
441+
442+
func testNSNull() {
443+
let jsonPath = NSBundle(forClass: self.dynamicType).pathForResource("Tests", ofType: "json")
444+
let jsonData = NSData(contentsOfFile: jsonPath!)
445+
let json = JSON(data: jsonData)
446+
447+
XCTAssertFalse(json["driver"].hasValue)
448+
}
449+
439450
// MARK: - Dictionary
440451

441452
func testDictionaryLiteralConvertible() {

ModelRocketTests/Tests.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"number_of_doors" : 4,
77
"zero_to_sixty_time" : 4.7,
88
"nav_system_standard" : true,
9+
"driver": null,
910
"manufacturer" : {
1011
"company_name" : "Bayerische Motoren Werke AG",
1112
"headquarters" : "Munich, Bavaria, Germany",
@@ -22,4 +23,4 @@
2223
"sedan" : 1024,
2324
"gran_coupe" : 512
2425
}
25-
}
26+
}

0 commit comments

Comments
 (0)