Monday, November 5, 2018

iOS Swift allow optional delegate methods possible?

Swift protocols on their side do not allow optional methods. But if you are making an app for macOS, iOS, tvOS or watchOS you can add the @objc keyword at the beginning of the implementation of your protocol and add @objc follow by optional keyword before each methods you want to be optional.

@objc protocol MyProtocol {
    @objc optional func anOptionalMethod()
}

A swiftier way
The problem with @objc is that you can not use it in pure Swift. For example, imagine that you make a library that can be used on linux to do some Back-end app with Swift. The @objc will not be available. But let’s remember why we would like to declare a protocol method as optional? It is because we we don’t want to write the implementation if that method will not be used. So Swift has a feature called extension that allow us to provide a default implementation for those methods that we want to be optional.

protocol MyProtocol {
    func anOptionalMethod()
    func aNotOptionalMethod()
}

extension MyProtocol {

    func anOptionalMethod() {
        //this is a empty implementation to allow this method to be optional
    }
}

references:
https://medium.com/@ant_one/how-to-have-optional-methods-in-protocol-in-pure-swift-without-using-objc-53151cddf4ce

No comments:

Post a Comment