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?
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.
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.
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
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