Search code examples
iosswiftuitableviewcell

Unwrapping UITableView cell text


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:

  1. value of optional type string? not unwrapped
  2. invalid character in source file

What is going on here? What else do I need to unwrap?


Solution

    1. There is no need to cast dequeueReusableCell to UITableViewCell since that is its return type.

    2. 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
    }