Associated types let you write flexible protocols that can work with different types. They act like placeholders for types that will be specified later.
Associated types in protocols in 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.
Item. It can hold any type of item.protocol Container { associatedtype Item mutating func append(_ item: Item) var count: Int { get } subscript(i: Int) -> Item { get } }
Container and specifies Item as Int.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] } }
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.
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])")
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.
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.