iOS

Init vs Convenience init in Swift

· 2 min read

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:

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.

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:

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.

Optional init

Both Designated init and Convenience init can return optional instance, which is nil.

Example of class

Example of struct