Sobes.tech
Junior — Middle

What is the purpose of extensions in protocols in the context of programming?

sobes.tech AI

Answer from AI

Extensions in protocols in iOS (Swift) allow adding new methods, properties, and functionality to existing types, including those that conform to protocols, without the need to modify the original source code of these types.

In the context of protocols, extensions allow:

  • Adding default implementations of methods so that all types conforming to the protocol can use them without mandatory implementation.
  • Extending protocols with additional methods that will be available to all implementing types.

This increases flexibility and reusability of code.

Example of a protocol extension:

protocol Greetable {
    func greet()
}

extension Greetable {
    func greet() {
        print("Hello from extension!")
    }
}

struct Person: Greetable {}

let p = Person()
p.greet() // Outputs: Hello from extension!

Thus, extensions allow setting default behavior and adding new capabilities to protocols.

What is the purpose of extensions in protocols in the… - sobes.tech