Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Protocol Associated Types in Swift
Written by Team Kodeco

In Swift, it’s possible to use associated types in a protocol to specify a placeholder type within the protocol. This allows a conforming type to provide a specific type for the associated type.

Here’s an example of how to use associated types in a protocol:

protocol Container {
  associatedtype Item
  var items: [Item] { get set }
  mutating func add(_ item: Item)
}

struct IntContainer: Container {
  var items = [Int]()
  mutating func add(_ item: Int) {
    items.append(item)
  }
}

var intContainer = IntContainer()
intContainer.add(3)
print(intContainer.items) // prints [3]

In this example, the Container protocol has an associated type called Item. The IntContainer struct conforms to the Container protocol and provides an implementation for the Item associated type, specifying that the items array should hold integers.

Here’s an example of a class that conforms to the Container protocol, but uses a different implementation for the Item associated type:

class StringContainer: Container {
  var items = [String]()
  func add(_ item: String) {
    items.append(item)
  }
}

var stringContainer = StringContainer()
stringContainer.add("hello")
print(stringContainer.items) // prints ["hello"]

In this example, the StringContainer class conforms to the Container protocol and provides an implementation for the Item associated type, specifying that the items array should hold strings.

Protocol associated types are useful when you want to create a protocol that describes a container, but you don’t know what type of items it will hold. It allows for the flexibility to use different types for the associated type depending on the implementation of the conforming type.

It’s important to note that when you use protocol associated types, the conforming type must provide an implementation for the associated type. Also, you can use the where clause to specify certain conditions that the associated type must conform to.

© 2024 Kodeco Inc.