SwiftQARandom

What's the difference between generics and Any or existentials?

A generic function like func first<T>(in array: [T]) -> T? is resolved at compile time — the compiler generates specialized code for each concrete type used (or uses a shared generic representation with witness tables), so the type is known statically and calls can be devirtualized and inlined.

Any, by contrast, is a type-erased box: the compiler has no idea what’s inside until runtime, so every operation on it needs dynamic type checks or casts, and there’s boxing overhead for anything larger than three words. Protocol existentials (any SomeProtocol) sit in between — they preserve some type information via witness tables but still involve indirection and dynamic dispatch, and in older Swift versions came with real cost from existential container boxing when the underlying type didn’t fit inline.

The practical answer: generics give you compile-time specialization and type safety with no runtime cost, so on a hot path — say, a Comparable-constrained sort routine reused across a data layer — you want generics over Any, and you’d only reach for any Protocol when you genuinely need heterogeneous storage, like an array holding different conforming types.