Junior — Middle
Explain the concept of using Generics in protocols and their application.
sobes.tech AI
Answer from AI
Generics in protocols allow creating abstract and reusable interfaces that work with different data types while maintaining type safety.
In Swift, for example, you can declare a protocol with an associated type (associatedtype), which acts as a placeholder for a specific type determined during protocol implementation.
Example:
protocol Container {
associatedtype Item
var count: Int { get }
subscript(i: Int) -> Item { get }
}
struct IntStack: Container {
var items = [Int]()
mutating func push(_ item: Int) {
items.append(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Int {
return items[i]
}
}
Here, Container is a protocol with a generic type Item. IntStack implements this protocol, specifying that Item is Int. This approach allows writing flexible and extensible code, where the type details are determined during implementation rather than in the protocol itself.