user523234 user523234 - 2 months ago 10
Swift Question

Type cast an instance of a class

Let's say I have two classes:


can be an instance from either of those two.

This one is no problem:

let firstVC = self.tabBarController?.viewControllers![0] as! FirstViewController

But this one gives error "classOfVC is not a type":

let aVC = self.tabBarController?.viewControllers![0]
let classOfVC = object_getClass(aVC)
let myVC = aVC as! classOfVC

Any suggestions?

Edit: I do not want to use isKindOfClass because I am trying to avoid using if ... else if... and since there are more than two classes envolved.


Type cast operator (as? or as!) is compile time operator. Type of any variable in Swift can't be dynamic as you intend to achieve with your cast.

You can't easily avoid if let, guard etc. In your your case you can do an explicit cast (as!), if you know that view controller at particular index never changes. But it is not recommended approach, usually you should tend to avoid using explicit casting.