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
- Generic Constraints and where Clauses
- Opaque Types with some Keyword
- Existentials with any and Type Erasure
- Primary Associated Types and Typed Throws