Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 898
David Silva Avatar asked Nov 12 '17 12:11

David Silva


1 Answers

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)
like image 123
Bilal Avatar answered Oct 22 '22 09:10

Bilal