Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Associated Types with Swift Generics
Written by Team Kodeco

In Swift, you can use associated types to define a placeholder name for a type within a protocol and that type can be specified when the protocol is adopted. To define an associated type, you use the associatedtype keyword before the placeholder type name.

Here’s an example of how to use associated types with generics in Swift:

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

struct Stack<T>: Container {
  var items = [T]()
  mutating func append(_ item: T) {
    items.append(item)
  }
  mutating func pop() -> T {
    return items.removeLast()
  }
  var count: Int {
    return items.count
  }
}

func printAndPop<U: Container>(container: inout U) {
  for _ in 0..<container.count {
    print(container.pop())
  }
}

var intStack = Stack<Int>()
intStack.append(1)
intStack.append(2)
intStack.append(3)
printAndPop(container: &intStack)

var stringStack = Stack<String>()
stringStack.append("Alice")
stringStack.append("Bob")
stringStack.append("Candice")
printAndPop(container: &stringStack)
// Output: 3
//         2
//         1
//         Candice
//         Bob
//         Alice

In this example, the Container protocol defines an associated type Item and several methods that operate on an array of Items. The Stack struct conforms to the Container protocol and specifies that its Item is of type T. This allows the Stack struct to be used with any type.

The printAndPop function takes a generic U that conforms to the Container protocol and a mutable reference to a U. It uses the count property and the pop() method to remove and print all items in the container.

The example also shows how to use the Stack struct with both Int and String types, demonstrating the flexibility and reusability of using associated types with generics in Swift.

© 2024 Kodeco Inc.