Search code examples
iosswiftobjectmapper

not assigning value to nested model in swift


trying to assign value to my model object but returns nil

my models :

struct Request:Mappable{


    var  id:String="" //
    var  origin:Location? 

}
  mutating func mapping(map: Map) {


        id <- map["id"]//
        origin <- map["origin"] //

}


struct Location :Mappable{

    var address=Address()


    mutating func mapping(map: Map) {

        address <- map["address"]

    }


var request=Request()
request.origin?.address.province?.id = "test" // assign nil

Solution

  • Suppose you have Address and Province types as below,

    struct Address {
        var province: Province?
    }
    
    struct Province {
        var id: String?
    }
    

    then to assign a value to province id, you need to setup the request as below,

    var request = Request()
    request.origin = Location()
    request.origin?.address.province = Province()
    request.origin?.address.province?.id = "test"