0
0
Swiftprogramming~5 mins

Associated types in protocols in Swift

Choose your learning style9 modes available
Introduction

Associated types let you write flexible protocols that can work with different types. They act like placeholders for types that will be specified later.

When you want a protocol to work with many types but don't know the exact type yet.
When you create a protocol for a container that can hold any kind of item.
When you want to write generic code that works with different data types.
When you want to define relationships between types inside a protocol.
Syntax
Swift
protocol ProtocolName {
    associatedtype ItemType
    func doSomething(with item: ItemType)
}

associatedtype declares a placeholder type inside a protocol.

The actual type is specified when a type adopts the protocol.

Examples
This protocol defines a container with an associated type Item. It can hold any type of item.
Swift
protocol Container {
    associatedtype Item
    mutating func append(_ item: Item)
    var count: Int { get }
    subscript(i: Int) -> Item { get }
}
This struct adopts Container and specifies Item as Int.
Swift
struct IntStack: Container {
    var items = [Int]()
    mutating func append(_ item: Int) {
        items.append(item)
    }
    var count: Int {
        items.count
    }
    subscript(i: Int) -> Int {
        items[i]
    }
}
Sample Program

This program defines a Container protocol with an associated type. The StringStack struct adopts it and uses String as the item type. It adds two strings and prints the count and first item.

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

struct StringStack: Container {
    var items = [String]()
    mutating func append(_ item: String) {
        items.append(item)
    }
    var count: Int {
        items.count
    }
    subscript(i: Int) -> String {
        items[i]
    }
}

var stack = StringStack()
stack.append("apple")
stack.append("banana")
print("Count: \(stack.count)")
print("First item: \(stack[0])")
OutputSuccess
Important Notes

Associated types let protocols be generic without using generics syntax everywhere.

You don't specify the associated type when defining the protocol, only when adopting it.

Use mutating keyword in protocol methods if the method changes the struct or enum.

Summary

Associated types are placeholders for types inside protocols.

They make protocols flexible and reusable with different types.

Types adopting the protocol specify the actual type for the associated type.