Marcus Leon Marcus Leon - 7 months ago 97
Swift Question

Swift: Convenience initializers - Self used before self.init call

We are getting the following error on the convenience method below:


Self used before self.init call


class MyClass {
var id : Int
var desc : String

init?(id : Int, desc : String) {
self.id = id
self.desc = desc
}

convenience init?(id : Int?) {
guard let x = id else {
return
}
self.init(id : x, desc : "Blah")
}
}


How can we implement this type of behavior in Swift?

Answer

As Leo already pointed out, the quickest way of appeasing the compiler is to return nil inside the guard statement.

convenience init?(id : Int?) {
    guard let x = id else {
        return nil
    }
    self.init(id: x, desc: "Blah")
}

Unless there is a specific reason to do so, you can also avoid using a failable initializer in the first place.init(id : Int, desc : String) compiles just fine.