user3689341 user3689341 - 8 months ago 39
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]
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:
fatal error: unexpectedly found nil while unwrapping an Optional value

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


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:

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