Using a Type Variable in a Generic

前端 未结 5 1554
迷失自我
迷失自我 2020-11-29 03:20

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         


        
5条回答
  •  孤独总比滥情好
    2020-11-29 03:50

    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:

    • Protocol-Oriented Programming in Swift
    • Building Better Apps with Value Types in Swift

    I found this slide particularly helpful for understanding protocols and dynamic dispatch:

提交回复
热议问题