Sobes.tech
Middle+

Which mechanism in Swift is similar to associated types?

sobes.tech AI

Answer from AI

Generics.

Associated types in protocols allow defining a placeholder name for a type within a protocol, which will be specified by a concrete type when adopting the protocol. This is very similar to how generics use placeholder type names (e.g., T) in functions, classes, or structures.

Example of an associated type:

protocol Container {
    associatedtype Item // Associated type
    mutating func append(_ item: Item)
    var count: Int { get }
    subscript(i: Int) -> Item { get }
}

Example of using a generic:

struct Stack<T> { // Generic type T
    var items: [T] = []
    mutating func push(_ item: T) {
        items.append(item)
    }
    mutating func pop() -> T {
        return items.removeLast()
    }
}

Both associated types and generics use a symbolic name for a type, which will be replaced with a specific type during usage. The main difference is that generics define a typed parameter for a structure, class, or function, while associated types specify a requirement for a type in a protocol that the conforming type must fulfill.

Which mechanism in Swift is similar to associated… - sobes.tech