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?
Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer's parameters set to default values.
Designated initializers are the default way of creating new instances of a type. There are others, known as convenience initializers, that are there to help you accomplish common tasks more easily, but those are in addition to your designated initializers rather than a replacement.
Conversely, if you write a subclass initializer that matches a superclass convenience initializer, that superclass convenience initializer can never be called directly by your subclass, as per the rules described above in Initializer Delegation for Class Types.
“If the initializer you are overriding is a convenience initializer, your override must call another designated initializer from its own subclass.”
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.
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