user3689341 user3689341 - 7 months ago 26
Swift Question

Strange unwrapping an optional error

Hi so I have a weird unwrapping optional error that I can not understand slash solve...

I created a new view controller to display meme details, added an image view to hold the memed image, however I kept getting unwrapping a nil error so to test I just added a label, an outlet to the label and then wrote this code:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let detailViewController = self.storyboard?.instantiateViewControllerWithIdentifier("MemeDetailViewController") as! MemeDetailViewController
let meme: Meme = appDelegate.memes[indexPath.row]
print(meme.topText)
detailViewController.label.text = meme.topText
//detailViewController.imageView.image = meme.memeImage
self.navigationController?.pushViewController(detailViewController, animated: true)
}


The top text for the meme is just TOP, and this is the console output:
TOP
fatal error: unexpectedly found nil while unwrapping an Optional value

Can someone please help me figure this out? Thanks in advance.

Answer

You are trying to set the text on the view controller's label before the label outlet has been connected (the label property is still nil)

Add this line of code:

print(meme.topText)
_ = detailViewController.view // This forces the view controller to load its view and connect its outlets
detailViewController.label.text = meme.topText