Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - what is downcasting? why do i need to downcast the cell in tableview?

The code below is to show the name of the cells in UItableview.

 override func tableView(tableView: UITableView,
        cellForRowAtIndexPath
        indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
            as UITableViewCell

        cell.textLabel!.text = "Spring \(indexPath.row + 1)"

        return cell
}

There is a compiling error and Xcode suggests me to change the line 'as' into 'as!'-

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
        as! UITableViewCell

May someone explains what is downcast and why do we need to downcast in this case?

like image 281
Cherry_thia Avatar asked Dec 19 '22 04:12

Cherry_thia


1 Answers

Because -dequeueReusableCellWithIdentifier: returns AnyObject (id in Objective-C). Swift needs you to force downcast because AnyObject can be any object and by force casting, you're telling the compiler to disregard the current type and force cast to a more specific object down the inheritance line.

like image 52
Schemetrical Avatar answered Mar 30 '23 01:03

Schemetrical