简体   繁体   中英

Why does my app crash when I use an “if let” statement to unwrap an optional collectionViewCell?

I am getting this error in xcode after months of this code working fine, and I can't for the life of me figure out why the code is throwing the error.

Error: Thread 1: Fatal Error: Unexpectedly found nil while unwrapping an Optional value

if let recentsRow = collectionView(collectionView, cellForItemAt: recentsIndex) as? DashboardRowCollectionViewCell {
        recentsRow.documents = recents ?? []
}

if let favoritesRow = collectionView(collectionView, cellForItemAt: favoritesIndex) as? DashboardRowCollectionViewCell {
        favoritesRow.documents = favorites ?? []
}

Sorry if this has already been asked, but I looked around the site for a while and still was unable to come up with a solution.

Edit: I do not have this issue when running the app in a simulator. I also didn't have this issue before I updated XCode.

Edit 2: The debugger has told me that collectionView is nil, but I am still unsure as to why it is nil.

Here is how collectionView is defined in my ViewController: @IBOutlet weak var collectionView: UICollectionView!

While I am not sure why the collectionview was nil in the first place, I fixed my application from crashing by surrounding the offending code with the following:

if collectionView != nil {
    ... code goes here ...
}

This will be the accepted answer until someone comes along to explain why it was nil to begin with.

Edit: If you are trying to figure out why it was nil and want the ViewController code that the problem belongs to, I'll be happy to provide it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM