Skip to content

Commit

Permalink
Merge pull request JohnSundell#94 from clayellis/master
Browse files Browse the repository at this point in the history
Unboxing string array to integer array. Fix #87
  • Loading branch information
JohnSundell authored Jul 26, 2016
2 parents c2ab085 + 7edfe75 commit f9c5a63
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
17 changes: 17 additions & 0 deletions Sources/Unbox.swift
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,23 @@ 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 rawValueArray = UnboxValueResolver<[T]>(self).resolveOptionalValueForKey(key, isKeyPath: isKeyPath) {
return rawValueArray
}

let transformedStringArray = UnboxValueResolver<[String]>(self).resolveOptionalValueForKey(key, isKeyPath: isKeyPath, transform: { stringArray -> [T]? in
var transformedStringArray = [T]()
for string in stringArray {
guard let transformedUnboxedString = T.transformUnboxedString(string) else { return nil }
transformedStringArray.append(transformedUnboxedString)
}
return transformedStringArray
})

if let transformedStringArray = transformedStringArray {
return transformedStringArray
}

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

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

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

struct ModelA: Unboxable {
let intArray: [Int]
init(unboxer: Unboxer) {
self.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 {
XCTFail()
}
}

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

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

do {
try Unbox(dictionary) as ModelA
XCTFail()
} catch {
// Test Passed
}
}

}

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

0 comments on commit f9c5a63

Please sign in to comment.