Required keyword usage in Swift classes and structs

The required keyword in Swift can be used in front of initializers in Swift. Its usage is simple and it’s a small use-case, but the usage of the keyword can easily be understood in the wrong way.

Required initializers

Some think that the required keyword makes only that initializer available when creating a class. Instead, it only requires you to implement that initializer into a subclass, but you can still use any other initializers.

A well-known example is the required decoder initializer within custom instances of a view controller. As soon as you add your own custom initializer, it will show you the following error:

The required decoder initializer in view controllers
The required decoder initializer in view controllers

Question is, why does it not show up without a custom initializer?

The following quote from the Swift documentation makes that clear:

You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer.

The default view controller class can no longer make sure that it decodes correctly. Therefore, a custom implementation is needed to handle possible new cases correctly.

Override modifier is not needed

Interesting to point out is that the override modifier is not needed for required initializers. However, the compiler will inform you with an error if you would add the keyword. The reason is that the modifier is implied when overriding a required initializer.

However, you must write the keyword before every subclass implementation. This is to indicate that the initializer requirement applies to further subclasses in the chain. This makes sense, as it would otherwise give the impression that the initializer is no longer necessary.

When should I use the keyword?

Whenever your class requires a certain setup when subclassed, mark the initializer as required. This makes sure that any new subclass instances will add support for that kind of usage. Subclassing is not possible when your class is marked as final. Therefore, the keyword is not needed.

The compiler will also require you to use it when implementing a protocol initializer.

More about Swift initializers

You can read more about Swift initializers in the free Swift Programming Language book or by reading the Swift documentation.


Originally published at SwiftLee.

More posts and updates: @twannl