Beginner’s guide to Swift Initializers-Part I

Samwel Charles
Backticks & Tildes
Published in
3 min readFeb 15, 2019

Initialization according to swift’s documentation “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 (_)

For this part 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.

Memberwise initializer provided automatically by Swift

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

Only our custom initializer is available now 😠

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 😉

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

CREDITS: SWIFT PROGRAMMING LANGUAGE BOOK

You can find more about me by following me on twitter or check out my github account

--

--