I'm trying to get the text on a table view cell and then get the index of it in an array.
This is the code I'm using:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
let indexOfCellString = event.index(of: cell.textLabel!.text)
}
But I get the following errors:
What is going on here? What else do I need to unwrap?
There is no need to cast dequeueReusableCell
to UITableViewCell
since that is its return type.
cell.textLabel
is optional. And then the text
property of UILabel
is optional.
Properly deal with optionals:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if let text = cell.textLabel?.text {
let indexOfCellString = event.index(text)
// do stuff with indexOfCellString
}
return cell
}