iosswiftoptional-parametersswift-protocolsswift-extensions

How does one declare optional methods in a Swift protocol?


Is it possible in Swift? If not then is there a workaround to do it?


Solution

  • 1. Using default implementations (preferred).

    protocol MyProtocol {
        func doSomething()
    }
    
    extension MyProtocol {
        func doSomething() {
            /* return a default value or just leave empty */
        }
    }
    
    struct MyStruct: MyProtocol {
        /* no compile error */
    }
    

    Advantages

    Disadvantages


    2. Using @objc optional.

    @objc protocol MyProtocol {
        @objc optional func doSomething()
    }
    
    class MyClass: NSObject, MyProtocol {
        /* no compile error */
    }
    

    Advantages

    Disadvantages