Sobes.tech
Junior — Middle

How can a common method be implemented to handle all collections that implement a certain protocol?

sobes.tech AI

Answer from AI

In Swift, you can define an extension for a protocol to add a common method that will be available to all types implementing that protocol. If you have a protocol that describes a collection, for example Collection, you can add a method in its extension.

Example:

extension Collection {
    func describe() -> String {
        return "The collection contains \(self.count) elements"
    }
}

let array = [1, 2, 3]
print(array.describe()) // The collection contains 3 elements

let set: Set = ["a", "b"]
print(set.describe()) // The collection contains 2 elements

Thus, all collections that conform to the Collection protocol automatically get the describe() method. This allows for centralized implementation of functionality for many types.