Tag:ios
Article From:https://segmentfault.com/q/1010000012143041
Question:

Development language: Swift3.2
The proxy method using CollectionView: didSelectItemAt, the wrong code is as follows

let cell:ChargeUpCollectionViewCell = collectionView.cellForItem(at: indexPath) as! ChargeUpCollectionViewCell

Error message: fatal error: unexpectedly found nil while unwrapping an Optional value

The specific error causing operation is to select a cell first, then slide the cell out of the screen, then click any cell, and the program will crash.

The same code will not be wrong if you use OC, and Swift3.2 will cause problems.

Answer 0:

The premise of Optional type mandatory unpacking is that you must know that its value must not be nil, otherwise it needs to be judged.

if let cell =  collectionView.cellForItem(at: indexPath) as? ChargeUpCollectionViewCell {
 // cellIt can be operated}

Answer 1:

Type strong should be written in this way

let cell = (collectionView.cellForItem(at: indexPath))! as ChargeUpCollectionViewCell

HoweverdidSelectItemAtReturn isUICollectionViewCell?Optional type, I suggest you addguardUnpack it.

guard let cell = collectionView.cellForItem(at: indexPath) else {
    return
}

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *