From 45fa82f2701e34545a4a098de83703a6a62295c8 Mon Sep 17 00:00:00 2001 From: Clay Ellis Date: Tue, 26 Jul 2016 11:48:00 -0600 Subject: [PATCH] Unboxing string array to integer array. Fix #87 Included tests. --- Sources/Unbox.swift | 14 ++++++++++++++ Tests/UnboxTests.swift | 21 +++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/Sources/Unbox.swift b/Sources/Unbox.swift index 1312cb1..05752e7 100644 --- a/Sources/Unbox.swift +++ b/Sources/Unbox.swift @@ -482,6 +482,20 @@ public class Unboxer { /// Unbox a required Array containing values of a raw type public func unbox(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: []) } diff --git a/Tests/UnboxTests.swift b/Tests/UnboxTests.swift index e7d74ab..fd8ad00 100644 --- a/Tests/UnboxTests.swift +++ b/Tests/UnboxTests.swift @@ -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 {