9

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?

David Silva
  • 1,939
  • 7
  • 28
  • 60

1 Answers1

16

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)
Bilal
  • 18,478
  • 8
  • 57
  • 72