Sobes.tech
Junior — Middle

Can you define a function inside a protocol definition?

sobes.tech AI

Answer from AI

In Swift, within a protocol definition, you cannot implement functions — protocols only specify requirements for methods, properties, and other members that must be implemented in classes, structures, or enumerations conforming to the protocol.

That is, in a protocol, you can declare a function signature, but not its body:

protocol MyProtocol {
    func doSomething()
}

The implementation of the doSomething() function must be provided in the type that adopts this protocol.

However, with the advent of protocol extensions, you can add default implementations of methods that will be available to all types conforming to the protocol:

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

Thus, you cannot define a function directly inside the protocol, but you can add an implementation in a protocol extension.

Can you define a function inside a protocol… - sobes.tech