Swift - what is a downgrade? why do i need to lower cell in tableview?

Below is the code showing the cell name in the 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 compilation error, and Xcode offers me to change the string 'as' to 'as!' -

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

Can someone explain what is dull, and why do we need to lower in this case?

+4
source share
4 answers

OK..let it's very easy to do.

In line:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell")

You get access to the method dequeueReusableCellWithIdentifier tableView, if you look at the documentation, you can see that the return type is AnyObject?.

Now suppose you want to access the property textLabelas

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

You cannot do this ... because not textLabelon AnyObjecttype.

, , UITableViewCell, , :

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

-dequeueReusableCellWithIdentifier: AnyObject (id Objective-C). Swift , downcast, AnyObject , , .

+5

, :

. , , (? !).

cast (!) , , downcast . , .

, ^ _ ^

+2

@Schemetrical -dequeueReusableCellWithIdentifier: return AnyObject, -tableView:cellForRowAtIndexPath: UITableViewCell .

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

, downcast, .

+2

All Articles