S
Samwel Charles

Beginners' guide to Swift initializers

Initialization is the process of preparing an instance of a class, structure or enumeration for use.

Initializers make sure an instance of a class or struct type is correctly setup before use

If you are from any other object-oriented programming language, you may be familiar with constructors, the same are known as initializers in Swift. When it comes to initializers in Swift, there are specific rules to be followed, that can not be easily bent.

Here are some rules that apply to both structs and classes.

  • All stored properties must have an initial value by the time an instance of a class or structure is created
  • Setting an initial value during initialization does not trigger property observers(willSet, didSet)
  • It’s not compulsory for optionals to have initial values since they default to nil
  • You can only set values to constant properties during initialization
  • If you want to take advantage of memberwise initializers along with your custom initializers, you’ll have to use extensions to define your custom initializers ( will be explained later)

Note: Swift will provide automatically argument labels for every parameter in the initializer, however if you do not wish to have argument labels in your initializers you can override them using underscore (_)

In part I we’ll look at Struct Initializers(Memberwise), In part II will look at initializers for classes.

Consider the following struct:

Above struct will have initializers created automatically (Memberwise initializer) and this is only true for struct types.

Initializer description

When you add your own custom initializer, you will lose memberwise initializer implicitly created for you by Swift like so:

Initializer description

After adding our own initializer we can no longer get memberwise initializers


However using extensions can solve this issue of losing memberwise initializers

With extensions we can define as many custom initializers as we want and still get memberwise initializer for free 😉

Initializer description

In part II we’ll explore initializers in class types, we’ll start with simple concepts an incrementally move to more advanced concepts

:: Published Apr 22, 2020 ::