So far we were able to make functions, methods, and types generic. Can we make protocols generic too? The answer is no, we cannot, but protocols support a similar feature named associated types. Associated types give placeholder names or aliases to types that are used as part of the protocol. The actual type to use for an associated type is not specified until the protocol is adopted. Associated types are specified with the associatedtype
keyword. Let's examine an example:
protocol Container { associatedtype ItemType mutating func append(item: ItemType) }
This protocol defines an append
function that takes any item of the ItemType
type. This protocol does not specify how the items in the container should be stored or what type they should be. The protocol only specifies an append
function that any type must provide in order to be considered a Container
.
Any type that conforms to the Container
protocol should be able to specify the type of values that it stores. Specifically, it must ensure that only items of the right type are added to the container.
To define these requirements, the Container
protocol requires a placeholder to refer to the type of elements that a container will contain, without knowing what that type is for a specific container. The Container
protocol needs to specify that any value passed to the append
method must have the same type as the container's element type.
To achieve this, the Container
protocol declares an associated type called ItemType
, written as associatedtype ItemType
.
The protocol does not define what ItemType
is an associatedtype
for, and this information is left for any conforming type to provide. Nonetheless, ItemType
associatedtype
provides you with a way to refer to the type of the items in a Container
and define a type to use with append
.
The following example shows how we will conform to a protocol with an associated type:
struct IntContainer: Container { typealias ItemType = Int mutating func append(item: ItemType) { // append item to the container } }
Here, we define a new struct
that conforms to the Container
protocol and takes Int
as ItemType
.