user3766930
user3766930

Reputation: 5829

my 'if let' construction throws NSException in Swift. Why?

In my swift app I have a block of code:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hashtagCell", for: indexPath) as! HashtagCollectionViewCell

    if let hashtagName:String =  self.suggestedHashtags[(indexPath as NSIndexPath).item] as? String {
        cell.hashtagName.text = hashtagName
    } else {
        cell.hashtagName.text = "emptyHashtag"
    }

    cell.hashtagName.textColor = UIColor.lightGray
    cell.hashtagName.font = font

    return cell

}

and this line:

if let hashtagName:String =  self.suggestedHashtags[(indexPath as NSIndexPath).item] as? String

sometimes crashes my app with the following error:

libc++abi.dylib: terminating with uncaught exception of type NSException

I thought that if let should handle this issue, but seems like it didn't. What might be the problem here?

Upvotes: 0

Views: 105

Answers (1)

vacawama
vacawama

Reputation: 154513

Your exception is likely index out of range. If your array might not be large enough to handle all items, you need to check. Something like this would work:

cell.hashtagName.text = "emptyHashtag"
if indexPath.item < suggestedHashtags.count {
    if let hashtagName = suggestedHashtags[indexPath.item] as? String {
        cell.hashtagName.text = hashtagName
    }
}

Upvotes: 2

Related Questions