jackdm jackdm - 1 month ago 8
Swift Question

Multiple methods to init object?

I have a model which uses init with JSON, so that i can create objects directly from an API response.

However in this instance I want to init the model and manually enter its properties, hence it wont be JSON.

How can i have another init method that allows me to not use the standard JSON method and instead manually enter my params?

The model looks like this...

class Conversation: NSObject {

var id: String
var index: String
var image: String
var firstname: String
var lastname: String
var withuserid: String
var badgeCount: String

init?(_ json: JSON) {
guard let id = json["id"].string,
let index = json["index"].string,
let image = json["image"].string,
let firstname = json["firstname"].string,
let lastname = json["lastname"].string,
let withuserid = json["withuserid"].string,
let badgeCount = json["badgeCount"].string

else { return nil }

self.id = id
self.index = index
self.image = image
self.firstname = firstname
self.lastname = lastname
self.withuserid = withuserid
self.badgeCount = badgeCount
}
}

Answer Source

Just add another init since you can several ones for a struct and class Then just call the desired one:

class Conversation: NSObject {
    var id: String
    var index: String
    var image: String
    var firstname: String
    var lastname: String
    var withuserid: String
    var badgeCount: String

    init?(_ json: JSON) {
        guard let id = json["id"].string,
            let index = json["index"].string,
            let image = json["image"].string,
            let firstname = json["firstname"].string,
            let lastname = json["lastname"].string,
            let withuserid = json["withuserid"].string,
            let badgeCount = json["badgeCount"].string

            else { return nil }

        self.id = id
        self.index = index
        self.image = image
        self.firstname = firstname
        self.lastname = lastname
        self.withuserid = withuserid
        self.badgeCount = badgeCount
    }

    init(id: String, index: String, image: String, firstName: String, lastName: String, withUserId: String, badgeCount: String) {
        self.id = id
        self.index = index
        self.image = image
        self.firstName = firstName
        self.lastName = lastName
        self.withUserId = withUserId
        self.badgeCount = badgeCount
    }
}