Search code examples
iosuitableviewswiftdetailtextlabel

App crashes if setting detailTextLabel of UITableViewCell


I'd like to set a value in the datailTextLabel of a UITableViewCell. If the code runs, the app crashes.

This is the error: fatal error: unexpectedly found nil while unwrapping an Optional value

This is the method in which the error takes place:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell

    cell.detailTextLabel!.text = "Date"      //error occurs

    return cell
}

Possible useful informations: https://www.dropbox.com/s/240sy3k1ic2hu0q/Bildschirmfoto%202015-02-28%20um%2021.03.35.png?dl=0


Solution

  • Use:

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
    

    Also, there is no need to force unwrap it. Even if detailTextLabel exists, I would use cell.detailTextLabel?.text = "Date" to be safe and make sure your cell is a style that supports detailTextLabel. Ie. Detail Left, Detail Right, Subtitle.