Swift: Convenience initializers - Self used before self.init call
15,750
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.
Related videos on Youtube
Author by
Marcus Leon
Director Clearing Technology, Intercontinental Exchange. Develop the clearing systems that power ICE/NYSE's derivatives markets.
Updated on May 08, 2020Comments
-
Marcus Leon almost 4 years
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?
-
Leo Dabus almost 8 yearsJust
return nil
-