Sobes.tech
Junior — Middle

Is it possible to implement optional methods in protocol definition?

sobes.tech AI

Answer from AI

In Swift, protocols can contain optional methods, but only if the protocol is declared with @objc and restricted to classes (i.e., inheriting from AnyObject). This is because optional methods are implemented through the Objective-C runtime mechanism.

Example:

@objc protocol MyProtocol {
    @objc optional func optionalMethod()
    func requiredMethod()
}

class MyClass: NSObject, MyProtocol {
    func requiredMethod() {
        print("Required method")
    }
    // optionalMethod is not mandatory to implement
}

If the protocol is not marked with @objc, all methods are considered mandatory and must be implemented.

Thus, implementing optional methods in protocols is possible but with restrictions related to the use of the Objective-C runtime.