#34: Optional Methods in Protocols

Swift protocols do not have optional requirements by default. On Apple platforms you can use Objective-C interoperability:

@objc protocol RefreshDelegate {
    @objc optional func didRefresh()
}

That only works with @objc-compatible protocols and classes.

A more Swifty alternative is usually a protocol extension with a default implementation:

protocol RefreshDelegate {
    func didRefresh()
}

extension RefreshDelegate {
    func didRefresh() {}
}

This keeps everything in pure Swift while still letting conforming types opt into the behavior they need.


I'm also on Twitter and GitHub.

Subscribe via RSS.