Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly cast to subclass in Swift?

I have a UITableView with a lot of different cells, based on whats in the content array of the datasource they should show custom content.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell : UITableViewCell? = nil
        let objectAtIndexPath: AnyObject = contentArray![indexPath.row]

        if let questionText = objectAtIndexPath as? String {
            cell = tableView.dequeueReusableCellWithIdentifier("questionCell", forIndexPath: indexPath) as QuestionTableViewCell
            cell.customLabel.text = "test"
        }

        return cell!
    }

Here I get the error that

UITableViewCell does not have the attribute customLabel

which QuestionTableViewCell does have. Whats wrong with my cast to QuestionTableViewCell?

like image 642
bogen Avatar asked Oct 18 '14 10:10

bogen


1 Answers

The problem is not your cast but your declaration of cell. You declared it as an optional UITableViewCell and that declaration remains forever - and is all that the compiler knows.

Thus you must cast at the point of the call to customLabel. Instead of this:

cell.customLabel.text = "test"

You need this:

(cell as QuestionTableViewCell).customLabel.text = "test"

You could make this easier on yourself by declaring a different variable (since you know that in this particular case your cell will be a QuestionTableViewCell), but as long as you are going to have just one variable, cell, you will have to constantly cast it to whatever class you believe it really will be. Personally, I would have written something more like this, exactly to avoid that repeated casting:

    if let questionText = objectAtIndexPath as? String {
        let qtv = tableView.dequeueReusableCellWithIdentifier("questionCell", forIndexPath: indexPath) as QuestionTableViewCell
        qtv.customLabel.text = "test"
        cell = qtv
    }
like image 191
matt Avatar answered Nov 11 '22 21:11

matt