Daniel
Daniel

Reputation: 3597

Getting UITableViewCell Properties From Cell Row

I have been trying to learn the ways of UITableViewControllers and I have been encountering an error. Here is the relevant part of my code:

class celly : UITableViewCell {
var name : String = ""
} 

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println(String((tableView.cellForRowAtIndexPath(indexPath.row) as! celly).name))
}

Here is the error for the second to last line (the println(...)). It is not the real error... I think :[)

Cannot find initializer for type 'String' that accepts an argument list of type '(String)' 

Does anybody know why my line is not working?

Thanks a lot in advance. Any help is greatly appreciated!

Upvotes: 0

Views: 37

Answers (2)

Zachary Espiritu
Zachary Espiritu

Reputation: 987

tableView.cellForRowAtIndexPath(indexPath.row) throws an error. The reason for this is that cellForRowAtIndexPath() takes an argument list of NSIndexPath, not an Int. By using indexPath.row, you're returning an Int rather than the required NSIndexPath. To fix this, simply remove the .row:

println((tableView.cellForRowAtIndexPath(indexPath) as! celly).name)

and you should be able to run it.

Upvotes: 0

Sulthan
Sulthan

Reputation: 130092

The error is incorrectly used row. Method tableView:cellForRowAtIndexPath: is accepting a NSIndexPath, so you have to call it with indexPath not with indexPath.row.

println(String((tableView.cellForRowAtIndexPath(indexPath) as! celly).name))

To spot similar errors easily, you might consider destructuring statements into simple and readable ones:

Destructuring:

let cell = tableView.cellForRowAtIndexPath(indexPath) as! celly
let name = cell.name

println(name)

The error message is a bug and I would consider report it.

Upvotes: 1

Related Questions