Swift’s static typing means the type of a variable must be known at compile time.
In the context of a generic function func foo<T>() { ... }
, T looks like a variable, but its type is actually known at compile time based on where the function is called from. The behavior of Array<T>()
depends on T
, but this information is known at compile time.
When using protocols, Swift employs dynamic dispatch, so you can write Array<MyProtocol>()
, and the array simply stores references to things which implement MyProtocol
— so when you get something out of the array, you have access to all functions/variables/typealiases required by MyProtocol
.
But if t
is actually a variable of kind Any.Type
, Array<t>()
is meaningless since its type is actually not known at compile time. (Since Array
is a generic struct, the compiler needs know which type to use as the generic parameter, but this is not possible.)
I would recommend watching some videos from WWDC this year:
I found this slide particularly helpful for understanding protocols and dynamic dispatch: