1.4 · Generics, <code>some</code>, <code>any</code>
Generics keep the concrete type known to the compiler. Existentials throw it away. Almost every performance and API-design question in this section is a consequence of that one difference.
Mental model. Generic = “the compiler knows the type, you do not need to.” Existential = “nobody knows the type, dispatch through a table.”
Generics vs existentials
Keep the type, or erase it.
- Generics vs protocols as types: when do you write
<T: P>(T)vsany P?
Use generics at API boundaries you control: the compiler keeps the concrete type, specializes the function, and can inline it. Zero existential cost. Use any P… some Viewvsany View— what is the difference, and why does SwiftUI usesome?
some View is an opaque type: one concrete type is chosen by the implementation and hidden from the caller. The compiler still knows it, so it can specialize…- What is the cost of
anyvssomeon a hot path?
any: the value may be boxed on the heap, every method call is indirect through a witness table, the caller cannot inline, and the existential container itself…
Opaque types
One hidden concrete type.
- What is the difference between
some Pas a parameter (Swift 5.7) and<T: P>?
For a single parameter they are almost identical: some P is an anonymous generic parameter. The differences: You cannot spell the type later — no way to… - What is the difference between
somein return position andsomein parameter position, historically?
Return position (Swift 5.1) is an opaque result type: the function picks one concrete type and hides it. The compiler still uses that exact type, which is why…
Under the hood
What the compiler and runtime actually build.
- What is an existential container? What is a witness table?
An existential (any P) is stored in a container with three parts: Value buffer — three words inline; larger values are boxed on the heap. Value witness table… - What is generic specialization? When does it not happen?
Specialization clones a generic function for a concrete T, replacing witness-table calls with direct calls and enabling inlining. It happens aggressively…
More in Swift language
- 1.1 · Value vs reference types
- 1.2 · Optionals, pattern matching, control flow
- 1.3 · Protocols, extensions, associated types
- 1.5 · Closures, escaping, capture lists
- 1.6 · Properties, observers, wrappers
- 1.7 · Access control
- 1.8 · Error handling, <code>defer</code>, ownership
- 1.9 · Strings and Unicode
- 1.10 · Codable, Sendable, macros, ABI
- 1.11 · Static vs dynamic dispatch