Skip to content

Commit

Permalink
Merge pull request #14 from alickbass/better-array-errors
Browse files Browse the repository at this point in the history
Add more verbose array errors
  • Loading branch information
Oleksii Dykan authored Jan 20, 2017
2 parents 65772b1 + 44e5214 commit ab1dad3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
8 changes: 7 additions & 1 deletion SwiftyJSONModel/JSONObject.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,13 @@ public extension JSONObject where PropertyType.RawValue == String {
let key = keyPath[0]
do {
if keyPath.count == 1 {
return try self[key].arrayValue().map({ try T(json: $0) })
return try self[key].arrayValue().enumerated().lazy.map({ index, json in
do {
return try T(json: json)
} catch let error as JSONModelError {
throw JSONModelError.invalidValueFor(key: String(index), error)
}
})
} else {
let subPath: [PropertyType] = .init(keyPath[1..<keyPath.count])
return try JSONObject<PropertyType>(json: self[key]).value(for: subPath)
Expand Down
8 changes: 7 additions & 1 deletion SwiftyJSONModelTests/JSONObjectTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,17 @@ class JSONObjectTests: XCTestCase {
}

XCTAssertEqual(try! object.value(for: .first, .second, .array), [1, 2, 3])
XCTAssertThrowsError(try object.value(for: .first, .second, .third) as [Int]) { error in
let first = PropertyKey.first.rawValue
let second = PropertyKey.second.rawValue
let third = PropertyKey.third.rawValue
XCTAssertEqual(error as? JSONModelError, .invalidValueFor(key: first, .invalidValueFor(key: second, .invalidValueFor(key: third, .invalidElement))))
}
XCTAssertThrowsError(try object.value(for: .first, .second, .array) as [String]) { error in
let first = PropertyKey.first.rawValue
let second = PropertyKey.second.rawValue
let array = PropertyKey.array.rawValue
XCTAssertEqual(error as? JSONModelError, .invalidValueFor(key: first, .invalidValueFor(key: second, .invalidValueFor(key: array, .invalidElement))))
XCTAssertEqual(error as? JSONModelError, .invalidValueFor(key: first, .invalidValueFor(key: second, .invalidValueFor(key: array, .invalidValueFor(key: "0", .invalidElement)))))
}

XCTAssertEqual(object.value(for: .first, .second, .third) as Int?, 3)
Expand Down

0 comments on commit ab1dad3

Please sign in to comment.