如何在Swift中正确转换为子类?

bog*_*gen 7 uitableview ios swift

我有一个UITableView有很多不同的单元格,基于数据源的内容数组中的什么,它们应该显示自定义内容.

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!
    }
Run Code Online (Sandbox Code Playgroud)

在这里我得到了错误

UITableViewCell does not have the attribute customLabel

QuestionTableViewCell确实有.我的演员QuestionTableViewCell怎么了?

mat*_*att 24

问题不是你的演员,而是你的宣言cell.您将其声明为可选的UITableViewCell,并且该声明永远保留 - 并且是编译器所知道的全部内容.

因此,必须转换在调用点customLabel.而不是这个:

cell.customLabel.text = "test"
Run Code Online (Sandbox Code Playgroud)

你需要这个:

(cell as QuestionTableViewCell).customLabel.text = "test"
Run Code Online (Sandbox Code Playgroud)

你可以通过声明一个不同的变量来让自己变得更容易(因为你知道在这种特殊情况下你的单元格将是一个QuestionTableViewCell),但只要你只有一个变量cell,你就必须经常抛出它无论你认为它真的会是什么课.就个人而言,我会写一些更像这样的东西,完全是为了避免重复投射:

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