user523234
user523234

Reputation: 14834

Type cast an instance of a class

Let's say I have two classes: FirstViewController and SecondViewController.

self.tabBarController?.viewControllers![0] 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.

Upvotes: 1

Views: 72

Answers (2)

Alexey Matjuk
Alexey Matjuk

Reputation: 4301

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.

Upvotes: 1

Nirav D
Nirav D

Reputation: 72410

You can use isKindOfClass to check the object of which class

let aVC = self.tabBarController?.viewControllers![0]   
if avc.isKindOfClass(FirstViewController) {
    //type of first ViewController
}
else if avc.isKindOfClass(SecondViewController) {
    //type of second ViewController
}

Upvotes: 1

Related Questions