Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectMapper - initialize object IOS

Simple thing that is giving me a headache - how to initialize an object that conforms to mappable protocol, without any JSON yet.

What I would like to do, is simply initialise empty User object in code like this:

let user = User()

however that gives me error: "missing argument for parameter #1 in call"

I was able to do it in version 0.14 with swift 1.2, but now it doesnt work. Do you guys know how to do it now in swift 2 and new Object Mapper ? (I know how to initialize it with json etc, I just want to initialize that object for other purposes and I cant figure out how)

class User: Mappable {
var username: String?
var age: Int?
var weight: Double!
var array: [AnyObject]?
var dictionary: [String : AnyObject] = [:]
var bestFriend: User?                       // Nested User object
var friends: [User]?                        // Array of Users
var birthday: NSDate?

required init?(_ map: Map) {

}

// Mappable
func mapping(map: Map) {
    username    <- map["username"]
    age         <- map["age"]
    weight      <- map["weight"]
    array       <- map["arr"]
    dictionary  <- map["dict"]
    bestFriend  <- map["best_friend"]
    friends     <- map["friends"]
    birthday    <- (map["birthday"], DateTransform())
}
}

please help!

like image 880
Ammo Avatar asked Nov 01 '15 22:11

Ammo


2 Answers

The following should work:

class User: NSObject, Mappable {
var username: String?
var age: Int?
var weight: Double!
var array: [AnyObject]?
var dictionary: [String : AnyObject] = [:]
var bestFriend: User?                       // Nested User object
var friends: [User]?                        // Array of Users
var birthday: NSDate?

override init() {
    super.init()
}

convenience required init?(_ map: Map) {
    self.init()
}

// Mappable
func mapping(map: Map) {
    username    <- map["username"]
    age         <- map["age"]
    weight      <- map["weight"]
    array       <- map["arr"]
    dictionary  <- map["dict"]
    bestFriend  <- map["best_friend"]
    friends     <- map["friends"]
    birthday    <- (map["birthday"], DateTransform())
}
}
like image 169
Sergey Demchenko Avatar answered Oct 17 '22 03:10

Sergey Demchenko


Fixed version of above answer:

init() {}
required convenience init?(_ map: Map) { self.init() }
like image 10
Andrey Toropchin Avatar answered Oct 17 '22 03:10

Andrey Toropchin