tristanhimmelman / ObjectMapper

Simple JSON Object mapping written in Swift
MIT License
9.16k stars 1.03k forks source link

Optional generics mapping fails #1093

Closed AlekseiR closed 4 years ago

AlekseiR commented 4 years ago

Say I have the following

Generic model:

struct ItemsExtractor<T: ImmutableMappable>: ImmutableMappable {
    let totalItems: Int
    let items: [T]

    init(map: Map) throws {
        self.totalItems = try map.value("totalItems")
        self.items = try map.value("items")
    }
}

My json:

{
        "object": {
        "totalItems": 0,
        "items": []
    }
}

Model:

struct MyModel: ImmutableMappable {
    let object: ItemsExtractor<SomeObject>?

    init(map: Map) throws {
        self.object = try? map.value("object")
    }
}

It doesn't actually matter what SomeObject looks like in this case, but..

Model:

struct SomeObject: ImmutableMappable {
    let id: String
    let name: String

    init(map: Map) throws {
        self.id = try map.value("id")
        self.name = try map.value("name")
    }
}

What I did:

let result = try Mapper<MyModel>().map(JSONObject: json)

What you expected:

I exepected something like:

MyModel(object: ItemsExtractor<SomeObject>) // with mapped fields

What you got:

MyModel(object: nil) // mapping doesn't happen even though the key is presented

If I use non-optional type of object in MyModel, all works as expected.

AlekseiR commented 4 years ago

Seems like it was fixed in one of updates. Closing the issue.