I have this question except for Swift. How do I use a Type variable in a generic?
I tried this:
func intType() -> Int.Type {
retu
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 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 depends on T, but this information is known at compile time.
When using protocols, Swift employs dynamic dispatch, so you can write Array, 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 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:
