Skip to content
tezvyn:

Associated Types: Making Protocols Generic

Source: docs.swift.orgMediumHow cards are made

Associated types make protocols generic. Think of them as a "fill-in-the-blank" type name. A protocol like Sequence has an Element type, which a conforming Array<String> fills in as String.

Why it exists

Protocols define a blueprint of methods and properties. But what if that blueprint needs to refer to another type that isn't known yet? Associated types solve this by allowing a protocol to be generic over types it uses, enabling powerful, flexible abstractions without specifying concrete types upfront.

The mental model

Think of an associated type as a placeholder or a "fill-in-the-blank" type name within a protocol. The protocol says, "Whoever adopts me must provide a concrete type for this placeholder I'm calling 'Item'." The conforming type then fills in that blank: "For me, 'Item' is a String."

How it works

You declare a protocol with the associatedtype keyword, giving the placeholder a name, for example, associatedtype Element. Methods, properties, and subscripts within the protocol can then refer to this Element type. When a concrete type like a struct or class conforms to the protocol, it specifies the actual type for Element. This can be done explicitly with a typealias or, more commonly, implicitly by implementing a required method or property whose signature uses a specific type.

When to use it

Use associated types when defining a protocol that describes a capability involving a type that isn't known until the protocol is adopted. The Swift Sequence and Collection protocols are prime examples; they have an Element associated type, allowing Array<String> and Set<Int> to share the same sequence-based logic while having different element types.

When not to use it

Using a protocol with an associated type (often called a "PAT") has a major restriction: you cannot use it as the concrete type for a variable, property, or array element (e.g., var myItems: [Container] is forbidden if Container has an associated type). This is because the compiler needs to know the exact size and type of Item at compile time. To work around this, you must use generic constraints (e.g., func process<C: Container>(_ container: C)) or a technique called type erasure (e.g., AnySequence<Int>).

One canonical example

A Container protocol might require conforming types to be able to hold some kind of item. It would declare associatedtype Item and then define methods like append(_ item: Item) and a count property. A Stack struct that holds integers could conform to Container. By implementing append(_ item: Int), it implicitly tells the compiler that for Stack, the Item associated type is Int.

Interview question

What is the primary reason to use an associated type within a Swift protocol?

  • a.To ensure that all types conforming to the protocol use the same specific type for a particular element.
  • b.To enable the protocol to refer to a type whose concrete definition is only known by conforming types.Correct
  • c.To permit the protocol itself to be used directly as a concrete type for variables and collections.
  • d.To allow the protocol to inherit generic parameters from a superclass or parent protocol.
Why?

Associated types exist to allow a protocol's blueprint to refer to a type that is not known until a concrete type adopts the protocol, making the protocol generic over types it uses. Option C is a tempting distractor because, while desirable, the card explicitly states that protocols with associated types cannot be used directly as concrete types for variables or collections without workarounds.

Just read this? Test yourself on what you have been reading.

Read the original → docs.swift.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on swift — each one lists the topics its interview covers.

See open roles