There are two ways to create optional protocol methods. One is with @objc tab, the other one uses the swift extension to provide a default method if not implemented.

I prefer using the second method.

Second Option (Preferred)

Using this way to create optional method in protocol, we are providing a default implementation for the protocol method.

1
2
3
4
5
6
7
8
9
10
protocol somethingDataSourceDelegate {
func getDataSourceSize() -> Int?
}

// provide default implementation for the protocol method
extension somethingDataSourceDelegate {
func getDataSourceSize() -> Int? {
return nil
}
}

First Option (Not Recommend)

For this option, we can create optional method in protocol using the old way by adding @objc attribute.

1
2
3
@objc protocol somethingDataSourceDelegate {
@objc func getDataSourceSize() -> Int
}