Search code examples
swiftswift3objectmapper

Creating new instance of object implementing Mappable interface


I am using ObjectMapper library to convert my model objects (classes and structs) to and from JSON.

But sometimes I would like to create objects without JSON.

Supposse, I have class like this:

class User: Mappable {
    var username: String?
    var age: Int?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        username    <- map["username"]
        age         <- map["age"]
    } 
}

I would like to create object without JSON, like this:

let newUser = User(username: "john", age: 18)

Is creating objects in this way possible for class implementing Mappable?


Solution

  • Add another init method with username and age as parameters.

    class User: Mappable {
        var username: String?
        var age: Int?
    
        init(username:String, age:Int) {
            self.username = username
            self.age = age
        }
    
        required init?(map: Map) {
    
        }
    
        func mapping(map: Map) {
            username    <- map["username"]
            age         <- map["age"]
        }
    }
    

    And use it like this.

    let user = User(username: "hello", age: 34)