Junior — Middle
Millised toimingud on saadaval protokolli laiendamisel laiendustega?
sobes.tech AI
Vastus AI-lt
In Swift, extensions allow adding new capabilities to existing types, including protocols. By extending a protocol with an extension, you can:
- Add default implementations of methods and properties, avoiding the need to implement these in each 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() // Prints: Hello from protocol extension!