Erfan
Erfan

Reputation: 161

Casting to a class which is determined at runtime

I want to know how to cast an object to a class that is determined only at runtime.

Let's use an example:

let xClasses = [ClassA.self, ClassB.self]
let xClass = xClasses[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! xClass

So basically, I have an array of classes and would like to choose from one of them at runtime for casting (In this example, an object of UITableViewCell).

(the above code does not work) How do I achieve this?

NOTE: I used this code as an example, my question is not only about UITableViewCell. Thanks.

Upvotes: 1

Views: 70

Answers (1)

Zac Kwan
Zac Kwan

Reputation: 5747

I have something like this in my project. I use a switch case to handle it. Something like this:

switch xClass {
case is ClassA:
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ClassACell
case is ClassB:
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ClassBCell
}

Most likely you will need to have a default: as well.

Type information that is being determine at runtime is actually called Existentials. You can read more information in this blog post. In swift2, You will have to use protocol if you does not want a switch case.

Upvotes: 1

Related Questions