0Pricing
Swift Academy · Lesson

Primary Associated Types and Typed Throws

Constraining protocol existentials and Swift 6 typed error propagation.

Primary Associated Types

Swift 5.7 lets you specify primary associated types on protocols, enabling constrained existentials.

protocol Container<Element> {
  associatedtype Element
  var items: [Element] { get }
}
struct Bag<T>: Container { var items: [T] = [] }

Constrained Existentials

With primary associated types you can write any Container to narrow the existential.

func printItems(_ c: any Container<Int>) {
  c.items.forEach { print($0) }
}
printItems(Bag(items: [1,2,3]))

All lessons in this course

  1. Generic Constraints and where Clauses
  2. Opaque Types with some Keyword
  3. Existentials with any and Type Erasure
  4. Primary Associated Types and Typed Throws
← Back to Swift Academy