diff --git a/MarshalTests/MarshalTests.swift b/MarshalTests/MarshalTests.swift index 4dfd266..7d7b1e4 100644 --- a/MarshalTests/MarshalTests.swift +++ b/MarshalTests/MarshalTests.swift @@ -185,6 +185,28 @@ class MarshalTests: XCTestCase { waitForExpectations(timeout: 1, handler: nil) } + func testOptionalArrayOfDictionaries() { + let jsonObject: JSONObject = ["not an array": 12] + + do { + let optArrayOfObjects: [JSONObject]? = try jsonObject.value(for: "who cares") + XCTAssertNil(optArrayOfObjects) + } catch { + XCTFail() + } + + let expectation = self.expectation(description: "type mismatch") + do { + let notAnArray: [JSONObject]? = try jsonObject.value(for: "not an array") + XCTFail("should have thrown instead of returning this: \(notAnArray)") + } catch { + if case MarshalError.typeMismatchWithKey = error { + expectation.fulfill() + } + } + waitForExpectations(timeout: 1, handler: nil) + } + func testSimpleArray() { let path = Bundle(for: type(of: self)).path(forResource: "TestSimpleArray", ofType: "json")! var data = try! Data(contentsOf: URL(fileURLWithPath: path)) diff --git a/Sources/MarshaledObject.swift b/Sources/MarshaledObject.swift index ced2a6f..a74c34b 100644 --- a/Sources/MarshaledObject.swift +++ b/Sources/MarshaledObject.swift @@ -137,6 +137,18 @@ public extension MarshaledObject { } return object } + + public func value(for key: KeyType) throws -> [MarshalDictionary]? { + do { + return try value(for: key) as [MarshalDictionary] + } + catch MarshalError.keyNotFound { + return nil + } + catch MarshalError.nullValue { + return nil + } + } public func value(for key: KeyType) throws -> MarshalDictionary { let any = try self.any(for: key) diff --git a/Sources/Operators.swift b/Sources/Operators.swift index f2a4b75..d7232b3 100644 --- a/Sources/Operators.swift +++ b/Sources/Operators.swift @@ -49,6 +49,12 @@ public func <| (dictionary: MarshaledObject, key: String) t public func <| (dictionary: MarshaledObject, key: String) throws -> JSONObject { return try dictionary.value(for: key) } +public func <| (dictionary: MarshaledObject, key: String) throws -> JSONObject? { + return try dictionary.value(for: key) +} public func <| (dictionary: MarshaledObject, key: String) throws -> [JSONObject] { return try dictionary.value(for: key) } +public func <| (dictionary: MarshaledObject, key: String) throws -> [JSONObject]? { + return try dictionary.value(for: key) +}