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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With