Skip to content

Commit

Permalink
Merge pull request #780 from devxoul/immutablemappable-as-property
Browse files Browse the repository at this point in the history
Add support to ImmutableMappable can become a property of Mappable
  • Loading branch information
tristanhimmelman authored Mar 27, 2017
2 parents 1a907fc + 64b4cc8 commit 6da5085
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
18 changes: 16 additions & 2 deletions Sources/Mapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,22 @@ public final class Mapper<N: BaseMappable> {
object.mapping(map: map)
return object
}
} else if N.self is ImmutableMappable.Type { // Check if object is ImmutableMappable
assert(false, "'ImmutableMappable' type requires throwing version of function \(#function) - use 'try' before \(#function)")
} else if let klass = N.self as? ImmutableMappable.Type { // Check if object is ImmutableMappable
do {
return try klass.init(map: map) as? N
} catch let error {
#if DEBUG
let exception: NSException
if let mapError = error as? MapError {
exception = NSException(name: .init(rawValue: "MapError"), reason: mapError.description, userInfo: nil)
} else {
exception = NSException(name: .init(rawValue: "ImmutableMappableError"), reason: error.localizedDescription, userInfo: nil)
}
exception.raise()
#else
NSLog("\(error)")
#endif
}
} else {
// Ensure BaseMappable is not implemented directly
assert(false, "BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable")
Expand Down
25 changes: 25 additions & 0 deletions Tests/ObjectMapperTests/ImmutableTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,31 @@ class ImmutableObjectTests: XCTestCase {
XCTAssertThrowsError(try Mapper<Struct>().mapArrayOfArrays(JSONObject: JSONArray))
}

func testAsPropertyOfMappable() {
struct ImmutableObject: ImmutableMappable {
let value: String
init(map: Map) throws {
self.value = try map.value("value")
}
}

struct Object: Mappable {
var immutable: ImmutableObject!
init?(map: Map) {}
mutating func mapping(map: Map) {
self.immutable <- map["immutable"]
}
}

let json: [String: Any] = [
"immutable": [
"value": "Hello"
]
]
let object = Mapper<Object>().map(JSON: json)
XCTAssertEqual(object?.immutable?.value, "Hello")
}

}

struct Struct {
Expand Down

0 comments on commit 6da5085

Please sign in to comment.