Required Initializers in Swift

Shantaram Kokate
3 min readApr 12, 2019

--

Required initializers play a crucial role when subclassing classes. You can decorate initializers with a required keyword. Adding the required keyword assures that subclasses implement the required initializer.

You need the required keyword for two reasons —

  1. Factory methods
  2. Protocols

Factory Methods

Introducing the draw factory method

The draw method accepts only String and returns an instance of Self. Self refers to the current type that the draw method is called on. this could be Shape class or one of its subclasses.

The reason that draw method returns Self is that Self is different for each subclass. If the method were to return a Shape instance, a draw wouldn’t be able to return an instance of Circle, Rectangle for example. But you’re not there yet. this gives the following error.

Error in creating the object

draw is calling the init(shape:) initializer on Shape or a Shape subclass. But how can the compiler be sure that a subclass will have an init(name:) initializer? The required designation will help the compiler to figure out it

The initializer throws an error because the draw method refers to self.init, it needs a guarantee that subclasses implement this method. Adding a required keyword to the designated initializer enforces subclasses to implement the initializer, which satisfies this requirement.

Solution :

First, you add the required keyword to the initializer in share method.

Adding the required keyword to initializers

2. Protocol

Protocols are the second reason the required keyword exists.

When a protocol has an initializer, a class adopting that protocol must decorate that initializer with the required keyword. Let’s see why and how this works.

First, you introduce a protocol called NameDelegate, which contains an initializer.

Implementing the NameDelegate protocol

At this point, the compiler still isn’t happy. Because Employee conforms to the NameDelegate protocol, its subclasses also have to conform to this protocol and implement init(name: String).

If you like this post, please share and give claps so others can find it 👏👏

You can follow me on Medium for updated articles. Also, connect with me on LinkedIn, Twitter.

If you have any comment, question, or recommendation, feel free to post them in the comment section below!👇

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shantaram Kokate
Shantaram Kokate

No responses yet

Write a response