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
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:
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.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.