Fatal error: unexpectedly found nil while unwrapping an Optional values

rulilg picture rulilg · Jul 9, 2014 · Viewed 260.7k times · Source

I was using an UICollectionView in Swift but I get when I try to change the text of the cell's label.

    func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int
{
    return 5
}

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
{
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("title", forIndexPath: indexPath) as TitleCollectionViewCell
    // Next line: fatal error: unexpectedly found nil while unwrapping an Optional value
    cell.labelTitle.text = "This is a title"
    return cell
}

Does anyone know about this?

Screenshot for warning on Console

Answer

Connor picture Connor · Jul 9, 2014

You can prevent the crash from happening by safely unwrapping cell.labelTitle with an if let statement.

if let label = cell.labelTitle{
    label.text = "This is a title"
}

You will still have to do some debugging to see why you are getting a nil value there though.