Initializers, also known as constructors in other programming languages, have two types: Designated init
and Convenience init
. They are used to initialize properties or customize a variable or object for classes or structs.
Designated init
This type of the Initializer is frequently seen in Swift class, also named as primary Initializer
- Designated initializers are the primary initializers for a class
- A class must have at least one
Designated initializer
- A struct can have
Designated initializers
, if not the compiler will automatically generate one with all properties - Used to initialize the property values
Example of designated init for a class:
![](https://needone.app/content/images/2021/02/image-2.png)
Example of designated init for a struct:
The compiler will automatically add a default initializer with all the properties, which is slightly different from class.
![](https://needone.app/content/images/2021/02/image-3.png)
Convenience init
Convenience initializers are secondary initializers for a class supporting a Designated initializer, which must call a Designated initializer
for a given class. Mostly used as a convenient way to call initializers. They:
- Can be override by subclass
- Must have at least one
Designated initializers
in the same class or from parent cla
Example of convenience init for a class:
![](https://needone.app/content/images/2021/02/image-7.png)
Example of convenience init for a struct:
convenience
is not required by struct, the reason is struct can't be inherited by another struct, so the struct init can only call the other init in the same struct.
![](https://needone.app/content/images/2021/02/image-6.png)
Optional init
Both Designated init
and Convenience init
can return optional instance, which is nil.
Example of class
![](https://needone.app/content/images/2021/02/image-8.png)
Example of struct
![](https://needone.app/content/images/2021/02/image-9.png)