Associated Type in Swift

In Swift, an associated type is a placeholder name for a type that is used as part of the protocol. The actual type to be used for the associated type is not specified until the protocol is adopted. Associated types are often used to specify the type of values that a protocol can work with, without specifying the exact type of those values.

Here’s an example of a protocol that uses an associated type:

protocol Container {
    associatedtype Item
    var items: [Item] { get set }
    mutating func append(_ item: Item)
    var count: Int { get }
    subscript(i: Int) -> Item { get }

In this example, the Container protocol defines an associated type called Item, which represents the type of the items that the container can hold. The protocol also defines several methods and properties that operate on the items array, but the type of the items in the array is not specified. It is up to the type that adopts the Container protocol to specify the actual type to be used for the Item associated type.

Here’s how the Container protocol might be adopted by a concrete type:

struct IntStack: Container {
    // specify the actual type to be used for the Item associated type
    typealias Item = Int

    var items: [Int] = []

    mutating func append(_ item: Int) {

    var count: Int {
        return items.count

    subscript(i: Int) -> Int {
        return items[i]

In this example, the IntStack type adopts the Container protocol and specifies that the Item associated type should be replaced with the Int type. This allows the IntStack type to use the Int type for the items in its items array, and to implement the methods and properties required by the Container protocol using the Int type.

Spread the love

Leave a comment