Cast to a Metatype Type in Swift?

后端 未结 1 1611
自闭症患者
自闭症患者 2021-01-04 19:32

Can you cast to a Metatype Type in Swift? It really seems like you should be able to (after all you can instantiate objects from Metatypes).

The following doesn\'t w

相关标签:
1条回答
  • 2021-01-04 19:48

    First of all, as takes a type, not an expression, on the right-hand side. So what you have is a syntax error.

    What you seem to be trying to do is "cast" to a type that is computed at runtime. What would that even mean? Let's first consider what is a "cast".

    Usually, when we have a cast expression x as T, it has two components:

    • At compile-time: The entire cast expression x as T has compile-time type T?, which allows you to do stuff with the resulting expression that you maybe cannot do on x directly. In other words, it allows you to change the compile-time type.
    • At runtime: It checks whether the runtime type of x is a subtype of T, and if it is, it evaluates to the optional containing that value, otherwise, it evaluates to nil.

    If the type T is not known at compile-time, then obviously you cannot do the compile-time part of it. (The compile-time type of the resulting expression cannot, obviously, depend on something which is not known at compile-time.)

    The other part, the runtime component, could that be done with a type computed at runtime? Sure. For example,

    import Foundation
    let afterCast : Super? =
        (superA as AnyObject).isKindOfClass(subType) ? superA : nil
    

    It's not clear if that is what you want.

    0 讨论(0)
提交回复
热议问题