Reputation: 44312
I have the following Swift code, which is mostly auto generated once a tableview is added:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "test")
return cell.textLabel.text = "test"
}
I get the following compile time error:
Cannot assign a value of type 'String' to a value of type 'String?'
I have tried !
(unwrapping) in the cell.textLabel.text
syntax to no effect. Any ideas what I'm doing wrong?
Upvotes: 0
Views: 1855
Reputation: 2967
The textLabel as a part of the UITableViewCell is optional and therefore you need to change your code to this:
cell.textLabel?.text = "test"
return cell
To add on to this you should not be getting your cell using that method, you should use:
let cell = tableView.dequeueReusableCellWithIdentifier("test", forIndexPath: indexPath) as UITableViewCell
So in the end your code should look like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("test", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "test"
return cell
}
Upvotes: 1
Reputation: 104082
You're supposed to be returning the cell, not text from cellForRowAtIndexPath. You also should be using dequeueReusableCellWithIdentifier to get your cell.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("test") as UITableViewCell!
cell.textLabel?.text = "test"
return cell
}
Upvotes: 2