Member-only story
2 Ways to Make Protocol Methods Optional in Swift
Learn the pros and cons of each approach

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: