Member-only story
Two-Phase Initialization in Swift
One then another
I’ve previously written about Swift initializers, however I didn’t EVEN MENTION Two-Phase Initilization.
Time to put that right!
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.5, and Swift 5.2.4
Prerequisites:
- You need to either be able to make a Single View Application in Swift, or use a Playground.
What is Swift’s Two-Phase Initialization
Swift has many safety features that allow us to have a great experience programming.
So what has Swift done to ensure that properties are set before a class
(or indeed a struct
) is ready for use?
The answer is the aforementioned Two-Phase Initialization: Two-phase initialization prevents property values from being accessed before they are are initialized, and prevent the property values from being set to a different value by another initializer unexpectedly.
The safety checks
Safety check 1
All properties introduced by it’s class are initalized before it delegates up to a superclass initializer.