How to define Optional Methods in the Swift Protocol?


This article will explain to you how to define optional methods in the protocol.

Before diving into making optional methods in the protocol, you will first learn what a protocol is and how to declare one in Swift.

What is The Protocol?

A protocol is a type that defines a group of methods or properties. Basically, you can define a blueprint of methods to specify behavior. A protocol is similar to interfaces in other programming languages.

Syntax

Here is the syntax of a simple protocol in Swift −

protocol <protocol_name> {
   // Properties
   // Methods
}

Basic Example

In this example, you will create a protocol called Person along with some properties and methods related to a person entity.

Here is an example of a person protocol in Swift −

protocol PersonProtocol { // Properties var id: String { get set } // Methods func fullName() -> String }

The PersonProtocol defines a property called id with getter and setter methods, and a method called fullName() that returns a string. To conform to this protocol, a type must implement both of these requirements.

Here is an example of a struct that conforms to the PersonProtocol protocol −

struct Employee: PersonProtocol { let firstName: String let lastName: String }

Now, if you compile the above code, you must get an error message like the following −

Type 'Employee' does not conform to protocol 'PersonProtocol'

The error message clearly states that the protocol called PersonProtocol does not conform properly. This error is coming because you have not implemented the required methods and properties in the Employee type.

This means you have to fulfill all the implementation requirements to comply with the protocol. You can change the code to look like this −

struct Employee: PersonProtocol { // MARK: - Properties let firstName: String let lastName: String // MARK: - PersonProtocol var id: String = UUID().uuidString func fullName() -> String { return firstName + " " + lastName } }

Notice here that whatever you have declared in the defined protocol must be implemented in the conforming type. But sometimes, it is not necessary to implement all the methods in the type.

Protocols can also specify optional requirements, which are methods or properties that a conforming type can choose to implement. Protocol Extension is the preferred way to mark methods or properties as optional.

Protocol extension is a way to provide the default implementation of methods or properties to make them optional. Despite the default implementation, a type conforming to the protocol can provide its own implementation of optional methods.

Let's look at an example to provide a default implementation of the protocol −

Let’s create another protocol like the following −

protocol Stack { var elementCount: Int { get } mutating func push(_ element: Int) mutating func pop() -> Int? }

In the above protocol, we define Stack with some properties and methods. Currently, all the methods are required to implement as below −

struct StackContainer: Stack { private var items: [Int] = [] var elementCount: Int { items.count } mutating func push(_ element: Int) { items.insert(element, at: 0) } mutating func pop() -> Int? { items.removeLast() } }

Now, you don't want to implement the pop() method in the type. So you can provide a default implementation of this method like the below −

extension Stack { mutating func pop() -> Int? { return nil } }

Implementation of type conformance might look like this −

struct StackContainer: Stack { private var items: [Int] = [] var elementCount: Int { items.count } mutating func push(_ element: Int) { items.insert(element, at: 0) } }

As you can see, the pop() method is no longer required to implement in the type.

Conclusion

The ability to extend an existing protocol with default behaviors is quite powerful. This allows protocols to grow and be extended without having to worry about breaking the compatibility of existing code.

Updated on: 03-Jan-2023

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements