JoshyJay
JoshyJay

Reputation: 53

Error with prepareForSegue ""unexpectedly found nil while unwrapping an Optional value""

I'm trying to pass data from a PFTableViewCell to the next view controller(details) with prepareForSegue function. I think I've put in the right code but when I run the app and click on the cell, my app crashes and I get this message "unexpectedly found nil while unwrapping an Optional value". I've tried many variations for the prepareForSegue function to pass the data but it would never appear on the next view controller.

In my FirstViewController I have this code written:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)  {
            if segue.identifier == "Detail" {
                if let destination = segue.destinationViewController as? ResponseViewController {
                let path = tableView?.indexPathForSelectedRow!
                let cell = tableView!.cellForRowAtIndexPath(path!) as! Post
                destination.name = (cell.name.text!)
                destination.message = (cell.message.text!)
              }

Here is the code to display the data passed in the ResponseViewController:

  var name = String?()
    var message = String?()

@IBOutlet weak var userName: UILabel!
@IBOutlet weak var userMessage: UILabel!

override func viewDidLoad() {
        super.viewDidLoad()
  userName.text! = name!
  userMessage.text! = message!
}

Now how do I fix this issue or better yet how can I prepareForSegue in swift 2.0?

Upvotes: 1

Views: 1561

Answers (1)

nielsbot
nielsbot

Reputation: 16022

One of your Optional variables contains nil.

Using '!' forces unwrapping of Optional values. If an Optional contains nil when it is unwrapped your program crashes with this error message. Try to avoid using force-casting (as!) and force-unwrapping.

Here's a nil safe version

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)  {
            if segue.identifier == "Detail" {
                if let destination = segue.destinationViewController as? ResponseViewController
                , path = tableView?.indexPathForSelectedRow
                , cell = tableView?.cellForRowAtIndexPath( path ) as? Post
            {
                destination.name = cell.name.text ?? "nil"
                destination.message = cell.message.text ?? "nil"
            }

and

var name: String?
var message: String?

@IBOutlet weak var userName: UILabel?
@IBOutlet weak var userMessage: UILabel?

override func viewDidLoad() 
{
    super.viewDidLoad()
    userName?.text = name ?? "nil"
    userMessage?.text = message ?? "nil"
}

N.b.:

  • ?? is the nil-coalescing operator. If the value on the left is nil, the value on the right is substituted.
  • You can optionally call methods on an optional value using the ?. accessor. If the value on the left is nil, the result will short-circuit to nil

Upvotes: 1

Related Questions