Skip to content
This repository has been archived by the owner on May 17, 2024. It is now read-only.

Commit

Permalink
Support Array Of Fields For Custom Transformation
Browse files Browse the repository at this point in the history
Returns `nil` if key doesn't exist or transformation for found value throws.
  • Loading branch information
dduan committed Oct 5, 2017
1 parent bc13fd2 commit 5e1ce76
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
17 changes: 17 additions & 0 deletions Sources/Mapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,23 @@ public struct Mapper {
return (try? transformation(try self.JSONFromField(field))).flatMap { $0 }
}

/// Get an optional typed value from the given fields by using the given transformation
///
/// - parameter fields: The array of fields to retrieve from the source data, can be an empty
/// string to return the entire data set
/// - parameter transformation: The transformation function used to create the expected value
///
/// - returns: The value of type T for the given field, if the transformation function doesn't throw
/// otherwise nil
public func optionalFrom<T>(_ fields: [String], transformation: (Any) throws -> T?) -> T? {
for field in fields {
if let value = try? transformation((try self.JSONFromField(field))) {
return value
}
}
return nil
}

// MARK: - Private

/// Get the object for a given field. If an empty string is passed, return the entire data source. This
Expand Down
48 changes: 48 additions & 0 deletions Tests/MapperTests/CustomTransformationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,52 @@ final class CustomTransformationTests: XCTestCase {
XCTFail("Shouldn't have failed to create Test")
}
}

func testOptionalCustomTransformationArrayOfKeys() {
struct Test: Mappable {
let value: Int?
init(map: Mapper) throws {
value = map.optionalFrom(["a", "b"], transformation: { thing in
if let a = thing as? Int {
return a + 1
}
throw MapperError.customError(field: nil, message: "")
})
}
}

let test = try? Test(map: Mapper(JSON: ["a": "##", "b": 1]))
XCTAssertEqual(test?.value, 2)
}

func testOptionalCustomTransformationArrayOfKeysFails() {
struct Test: Mappable {
let value: Int?
init(map: Mapper) throws {
value = map.optionalFrom(["a", "b"], transformation: { thing in
throw MapperError.customError(field: nil, message: "")
})
}
}

let test = try? Test(map: Mapper(JSON: ["a": "##", "b": 1]))
XCTAssertNil(test?.value)
}

func testOptionalCustomTransformationArrayOfKeysReturnsNil() {
struct Test: Mappable {
let value: Int?
init(map: Mapper) throws {
value = map.optionalFrom(["a", "b"], transformation: { thing in
if let a = thing as? Int {
return a + 1
}
throw MapperError.customError(field: nil, message: "")
})
}
}

let test = try? Test(map: Mapper(JSON: [:]))
XCTAssertNil(test?.value)
}
}

0 comments on commit 5e1ce76

Please sign in to comment.