Skip to content

Commit

Permalink
Unboxing string array to integer array. Fix #87
Browse files Browse the repository at this point in the history
Included tests.
  • Loading branch information
clayellis committed Jul 26, 2016
1 parent c2ab085 commit 45fa82f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Sources/Unbox.swift
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,20 @@ public class Unboxer {

/// Unbox a required Array containing values of a raw type
public func unbox<T: UnboxableRawType>(key: String, isKeyPath: Bool = true) -> [T] {
if let rawValue = UnboxValueResolver<[T]>(self).resolveOptionalValueForKey(key, isKeyPath: isKeyPath) {
return rawValue
}

let transformedStringArray = UnboxValueResolver<[String]>(self).resolveOptionalValueForKey(key, isKeyPath: isKeyPath, transform: { stringArray -> [T]? in
return stringArray.flatMap {
return T.transformUnboxedString($0)
}
})

if let transformedStringArray = transformedStringArray {
return transformedStringArray
}

return UnboxValueResolver<[T]>(self).resolveRequiredValueForKey(key, isKeyPath: isKeyPath, fallbackValue: [])
}

Expand Down
21 changes: 21 additions & 0 deletions Tests/UnboxTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1358,6 +1358,27 @@ class UnboxTests: XCTestCase {
}
}

func testUnboxingArrayOfStringTransformedToInt() {
let dictionary: UnboxableDictionary = ["intArray": ["123", "456", "789"]]

struct ModelA: Unboxable {
let intArray: [Int]
init(unboxer: Unboxer) {
intArray = unboxer.unbox("intArray")
}
}

do {
let modelA: ModelA = try Unbox(dictionary)
XCTAssertEqual(modelA.intArray[0], 123)
XCTAssertEqual(modelA.intArray[1], 456)
XCTAssertEqual(modelA.intArray[2], 789)
} catch {
print(error)
XCTFail()
}
}

}

private func UnboxTestDictionaryWithAllRequiredKeysWithValidValues(nested: Bool) -> UnboxableDictionary {
Expand Down

0 comments on commit 45fa82f

Please sign in to comment.