Sobes.tech
Junior — Middle

Is it possible to define the implementation of methods within a protocol?

sobes.tech AI

Answer from AI

In Swift, protocols can declare methods but not their implementations. However, with the introduction of extensions, you can add default method implementations to protocols, which are then available to all types conforming to the protocol.

Example:

protocol MyProtocol {
    func doSomething()
}

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

struct MyStruct: MyProtocol {}

let obj = MyStruct()
obj.doSomething() // Prints: Default implementation

Thus, protocols themselves do not contain implementations, but extensions can provide default implementations for protocol methods.