Better Programming

Advice for programmers.

Follow publication

Member-only story

2 Ways to Make Protocol Methods Optional in Swift

Zafar Ivaev
Better Programming
Published in
2 min readJul 14, 2020
Image by Free-Photos from Pixabay

In this article, we’ll learn about two ways to make protocol methods optional. We’ll explore the advantages and disadvantages of each approach.

Without further ado, let’s get started.

Default Implementation

The first approach is to create an extension of a protocol and include an empty method of the protocol:

This way we make the didDismiss() method optional. Let’s see what happens when we conform to the PickerViewDelegate protocol:

The compiler doesn’t require us to implement the didDismiss() method.

Advantages

  • We can also conform structures to a protocol
  • Default implementation inside the extension is automatically used when we don’t implement the method inside the conforming type

Disadvantages

  • In cases when an optional method returns a non-Void value, we’ll need to come up with and return some value inside the default implementation

Objective-C ‘optional’ Keyword

We can mark the protocol with the @objc keyword and the optional method with @objc optional:

This way, we don’t need to create an extension — all we need to do is conform a class to the protocol:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Zafar Ivaev
Zafar Ivaev

Written by Zafar Ivaev

Senior iOS Engineer. I write about features of Swift and iOS development practices.

Responses (2)

Write a response