Creating optional protocol method in swift

ยท

2 min read

If you are coming from Obj-C to Swift, you might have realized that there is no optional keyword available in Swift to define an optional protocol method in Swift Protocols.

We can achieve it via @objc attribute. But in this post, I will discuss the alternative way of achieving it in a purely swift way using the power of extension.

Using protocol extension we can provide a default implementation of the method we want to treat as optional. This will allow user to opt out the implementation of the method as there is a default implementation provided for it.

Let us take following example from JNDropDownMenu library:

public protocol JNDropDownMenuDataSource: class {
func numberOfRows(in column: NSInteger, for menu: JNDropDownMenu) -> Int
func titleForRow(at indexPath: JNIndexPath, for menu: JNDropDownMenu) -> String
func numberOfColumns(in menu: JNDropDownMenu) -> NSInteger
func titleFor(column: Int, menu: JNDropDownMenu) -> String
}

In above protocol, I wanted to keep the last two methods optional. To do that I can provide a default implementation of it in the protocol extension as follow:

public extension JNDropDownMenuDataSource {
func numberOfColumns(in menu: JNDropDownMenu) -> NSInteger {
return 1
}
func titleFor(column: Int, menu: JNDropDownMenu) -> String {
return menu.datasource?.titleForRow(at: JNIndexPath(column: column, row: 0), for: menu) ?? ""
}
}

Due to this default implementation, you are now allowed to opt out these methods in the class conforming to this protocol and can implement it only if you want to override the default implementation and provide your own value.

Hope this helps you to achieve the optional behavior in a pure Swift way.

Happy Coding! ๐Ÿ™‚

Did you find this article valuable?

Support Javal Nanda by becoming a sponsor. Any amount is appreciated!

ย