Swift Shortcuts #1 — Adding new Constructors to structs

Nicolas Nascimento
Swift Developer Academy Porto Alegre
3 min readJul 23, 2020

Structs in Swift

In Swift, structs are (or should be) the go-to abstraction used to store properties or methods. This is due to many aspects, such as their value-type semantics.

One of the most interesting aspects of Swift structs is that they enable the compiler to auto-synthesize constructors (or initializers).

For example, below we define a struct Person with a property name and use the compiler-generated initializer to create a new instance.

The problem with defining new Constructors

Compiler-generated init functions are great but what if we add our own initializer? A no-paramater initializer, for example.
The simplest way to do so is define an custom init inside the declaration of the struct.

The bad part of this approach is that now that we have defined our own initializer, the compiler has not been able to auto-generate the default init function. Thus, our struct has only one valid initialization method, the one we defined.

This particular case of empty initialization can be solved by setting default values to our properties. This was, we can have two initializer provided by the compiler.

Adding new Constructors

Now this are still auto-generated inits, what if we actually want to add a new constructor that receives parameters, can we still keep the compiler-generated init functions?

Well, turns out we can! Swift allows us to add new constructors to structs and still keep the compiler-generated ones by using extensions.

If we extend a struct and define a custom initializer, the compiler can synthesize the default initializers and we get our custom constructor.

In our example, we can add a custom init.

And now we have three ways to initialize our struct!

As a result, our final implementation is presented below.

Summary

One of the nicest features of structs in Swift is they can have their initializers generated by the compiler. We often want to add our own init function thought, but keeping these auto-generated inits can be quite useful. As such, a great way to have custom constructors while maintaining the compiler-generated ones is through extensions.

If you want to see this feature in action through a video, check out the links below.

--

--