When to use existentials (any P) vs generics
Choose between any P (existential types) and generics : heterogeneous storage & dynamic behavior vs compile-time specialization & static guarantees.
Existentials vs generics
Existentials (any P) store values of unknown concrete type that conform to a protocol. Generics (<T: P>) keep the concrete type at compile time for specialization.
Protocol setup
Protocols without associated types are easy to use as any P existentials and as generic constraints.
protocol Animal {
func speak() -> String
}
struct Dog: Animal { func speak() -> String { "woof" } }
struct Cat: Animal { func speak() -> String { "meow" } }All lessons in this course
- associatedtype & generic protocols
- Type erasure patterns (AnySequence/AnyIterator)
- When to use existentials (any P) vs generics