Check if optional protocol method is implemented in Swift? Check if optional protocol method is implemented in Swift? ios ios

Check if optional protocol method is implemented in Swift?


Per The Swift Programming Language:

You check for an implementation of an optional requirement by writing a question mark after the name of the requirement when it is called, such as someOptionalMethod?(someArgument). Optional property requirements, and optional method requirements that return a value, will always return an optional value of the appropriate type when they are accessed or called, to reflect the fact that the optional requirement may not have been implemented.

So the intention is not that you check whether the method is implemented, it's that you attempt to call it regardless and get an optional back.


You can do

if delegate?.myFunction != nil {}


I've found it successful to add an extension to the protocol that defines basic default implementation and then any class implementing the protocol need only override the functions of interest.

    public protocol PresenterDelegate : class {        func presenterDidRefreshCompleteLayout(presenter: Presenter)        func presenterShouldDoSomething(presenter: Presenter) -> Bool    }

then extend

    extension PresenterDelegate {        public func presenterDidRefreshCompleteLayout(presenter: Presenter) {}        public func presenterShouldDoSomething(presenter: Presenter) -> Bool {        return true        }    }

Now any class needing to conform to the PresenterDelegate protocol has all functions already implemented, so it's now optional to override it's functionality.