WasimSafdar WasimSafdar - 3 months ago 15
Swift Question

unexpectedly found nil while unwrapping an Optional value prepareForSegue

I am beginner in swift and working on one project where I am using collectionView. From collectionView, I want to transfer some values to details view but I am getting the above mentioned error. Values are not nil but somehow, it is giving this error while performing segue. Anybody help me, I am badly stuck here.

//In my CollectionView Controller.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if(segue.identifier == "DetailsView")
{
if let vc:DetailsViewController = segue.destinationViewController as? DetailsViewController
{
vc.details.text = self.description
vc.line.text = self.subText
vc.startTime.text = self.formatted_time
}
}
}

//DetailsViewController
import UIKit

class DetailsViewController: UIViewController {

@IBOutlet var startTime: UILabel!
@IBOutlet var line: UILabel!
@IBOutlet var details: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()
}

}

Answer

This basically means your IBOutlet are not yet initialised.

You should set strings and then in the viewDidLoad set you labels. So to sum up:

  1. Add string properties in your details view
  2. Set these string properties in your preparForsegue function
  3. in the viewDidLoad of your detail controller, set your labels

Your code should look like something like this :

//In my CollectionView Controller.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if(segue.identifier == "DetailsView")
    {
        if let vc:DetailsViewController = segue.destinationViewController as? DetailsViewController
        {
            vc.detailsString = self.description
            vc.lineString = self.subText
            vc.startTimeString = self.formatted_time
        }
    }
}

//DetailsViewController
import UIKit

class DetailsViewController: UIViewController {

    @IBOutlet var startTime: UILabel!
    @IBOutlet var line: UILabel!
    @IBOutlet var details: UILabel!

    var startTimeString: String?
    var lineString: String?
    var detailsString: String?

    override func viewDidLoad() {
        super.viewDidLoad()


            startTime.text = tmpStartTimeString
            line.text = tmpLineString
            details.text = tmpDetailsString

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()
    }

}

Double check my code, I've wrote it very quickly ;)

Comments