Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 610
Marcus Leon Avatar asked May 08 '16 01:05

Marcus Leon


People also ask

What must a convenience initializer call 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.

What is use of convenience Initializers?

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.

Can we override convenience init Swift?

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.

Can you override a convenience init?

“If the initializer you are overriding is a convenience initializer, your override must call another designated initializer from its own subclass.”


1 Answers

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.

like image 61
Smnd Avatar answered Oct 04 '22 23:10

Smnd