Give your simulator superpowers

RocketSim: An Essential Developer Tool
as recommended by Apple

Optional protocol methods in Swift

In Swift it’s kind of unsupported to implemented optional protocol methods.

You can, which is ugly, use the @objc syntax:

@objc protocol MyProtocol {
    optional func doSomething();
}

class MyClass : MyProtocol {
    // no error
}

Another disadvantage here is that structs are unsupported, as you’re bridging for Objc.

Stay updated with the latest in Swift

Join 20,010 Swift developers in our exclusive newsletter for the latest insights, tips, and updates. Don't miss out – join today!

You can always unsubscribe, no hard feelings.

Using protocol extensions to create optional protocol methods

However, with Swift 2.0 it’s possible to define protocol extension. This allows you to create optional methods for your protocol easily:

protocol MyProtocol {
    func doSomethingNonOptionalMethod()
    func doSomethingOptionalMethod()
}

extension MyProtocol {
    func doSomethingOptionalMethod(){ 
        // leaving this empty 
    }
}

As stated in this thread, many people are asking this feature:
http://stackoverflow.com/questions/24032754/how-to-define-optional-methods-in-swift-protocol

 
Antoine van der Lee

Written by

Antoine van der Lee

iOS Developer since 2010, former Staff iOS Engineer at WeTransfer and currently full-time Indie Developer & Founder at SwiftLee. Writing a new blog post every week related to Swift, iOS and Xcode. Regular speaker and workshop host.

Are you ready to

Turn your side projects into independence?

Learn my proven steps to transform your passion into profit.