Junior — Middle
What actions are available when extending the protocol with extensions?
sobes.tech AI
Answer from AI
In Swift, extensions allow adding new capabilities to existing types, including protocols. When extending a protocol with an extension, you can:
- Add default implementations of methods and properties, which avoids the need to implement these methods in every type that conforms to the protocol.
- Add computed properties.
- Add new methods that will be available to all types conforming to the protocol.
However, protocol extensions do not allow adding new requirements (such as new mandatory methods or properties), only default implementations.
Example:
protocol Greetable {
func greet()
}
extension Greetable {
func greet() {
print("Hello from protocol extension!")
}
}
struct Person: Greetable {}
let p = Person()
p.greet() // Outputs: Hello from protocol extension!