Initialization is hugely important in any modern language. This is not a full guide (Apple have provided a long guide, which is referenced below) but rather a shorter example-laden walk through initialization for Swift.
Before we start
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12.2, and Swift 5.3
- Some understanding of OO concepts
- Some idea of Structs and Classes in Swift
Initializers: Called to create a new instance of a type, be it a struct, enum or a class.
Initializer delegation: Where an initializer calls other initializers to perform part of an instances initialization.
Initializers for structs — the default initializer
An initializer can easily be created within a struct (note that the internal and external names are usually the same in an initializer)
However, Swift has a memberwize initializer (so long as you do not provide a single initializer).
We can also call another initializer to perform the initialization (or part of it). This is called initializer delegation.
Designated initializers for a simple class