yzet00
yzet00

Reputation: 511

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?

Upvotes: 15

Views: 8699

Answers (6)

Jignesh Radadiya
Jignesh Radadiya

Reputation: 68

 CMessageCell=self.MessageTable.dequeueReusableCellWithIdentifier("CustomMessageCell") as! CustomMessageCell

Upvotes: 0

Or Assraf
Or Assraf

Reputation: 634

if you want to use identifier you should use those methods :

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 100
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("WHAT-EVER-YOU-WANT-TO-CALL-IT", forIndexPath: indexPath)
    let label = cell.viewWithTag(1000) as! UILabel
}
    return cell 

Upvotes: -1

Kelvin Lau
Kelvin Lau

Reputation: 6781

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") }

Upvotes: 3

Lifu  Lin
Lifu Lin

Reputation: 79

var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as UITableViewCell!

Upvotes: -2

Tyler
Tyler

Reputation: 34

Use this instead

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

Upvotes: 0

Long Pham
Long Pham

Reputation: 7582

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!

Upvotes: 30

Related Questions