Sobes.tech
Junior — Middle

Are all functions declared in the protocol mandatory to implement for the class that implements it?

sobes.tech AI

Answer from AI

In Swift, all functions declared in a protocol are, by default, required to be implemented by the class that adopts this protocol. However, if the protocol specifies methods with default implementations through an extension, then implementing such methods in the class becomes optional.

Example:

protocol MyProtocol {
    func requiredMethod()
    func optionalMethod()
}

extension MyProtocol {
    func optionalMethod() {
        print("Default implementation")
    }
}

class MyClass: MyProtocol {
    func requiredMethod() {
        print("Implemented required method")
    }
    // optionalMethod does not need to be implemented
}

Thus, only methods without default implementations in the protocol are mandatory.

Are all functions declared in the protocol mandatory… - sobes.tech