Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call methods from Swift initializer

Tags:

swift

Let's say I have the following class in Swift (which has obvious problems)

class MyClass {     let myProperty: String      init() {         super.init()         self.setupMyProperty()     }      func setupMyProperty() {         myProperty = "x"     } } 

This is overly simplified but I'm basically trying to delegate the initialization of myProperty into the setupMyProperty() method. It's a pattern I use often to break down the different parts of the setup of a class.

But of course, I can't call self until the super initializer has run, and I can't run the super initializer until all the properties have been set, so I'm in a catch 22. On top of it since setupMyProperty() isn't considered an initializer, it won't be able to assign myProperty anyway.

Can anyone tell me how to implement this pattern in Swift?

like image 968
mprivat Avatar asked Jun 09 '14 11:06

mprivat


People also ask

What does init () do in Swift?

Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.

What must a convenience initializer call?

The convenience initializer must call one of the two designated initializers, because it can only call another initializer from the same class. This satisfies rules 2 and 3 from above. Both designated initializers must call the single designated initializer from the superclass, to satisfy rule 1 from above.


1 Answers

declare it as an implicitly unwrapped optional

class MyClass : NSObject {     var myProperty: String!      init() {         super.init()         self.setupMyProperty()     }      func setupMyProperty() {         self.myProperty = "x"     } } 

page 499 of "The Swift Programming Language" manual

like image 111
LombaX Avatar answered Oct 03 '22 20:10

LombaX