Junior — Middle
Is it possible to define a default implementation of a method in an interface or protocol?
sobes.tech AI
Answer from AI
In Swift, protocols can contain default method implementations through extensions. This allows setting a default behavior for protocol methods, which can be overridden in specific types.
Example:
protocol Greetable {
func greet()
}
extension Greetable {
func greet() {
print("Default greeting")
}
}
struct Person: Greetable {}
let p = Person()
p.greet() // Will output: Default greeting
Thus, the default implementation is set not in the protocol itself, but in its extension.