Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableVIewCell Error Xcode 7 / Swift 2

I ran into the following error in this code:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell

ERROR: Downcast from 'UITableViewCell?' to 'UITableViewCell' only unwraps optionals; did you mean to use '!'?

Any Ideas?

like image 771
yzet00 Avatar asked Aug 02 '15 17:08

yzet00


2 Answers

In Swift2.0 method dequeueReusableCellWithIdentifier is declare as:

@available(iOS 6.0, *)
func dequeueReusableCellWithIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath) -> UITableViewCell

You shouldn't cast UITableViewCell to UITableViewCell?. See code below.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)

    // Configure the cell...

    return cell
}

Hope this helps!

like image 140
Long Pham Avatar answered Sep 28 '22 16:09

Long Pham


As of Xcode 7, dequeueReusableCellWithIdentifier will always return a non optional UITableViewCell.

You don't even need to specify the type, it can be written succinctly as:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell")

or if you have a custom subclass of UITableViewCell

guard let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? SomeOtherCell else { fatalError("unexpected cell dequeued from tableView") }
like image 37
Kelvin Lau Avatar answered Sep 28 '22 15:09

Kelvin Lau