Sauron Sauron - 7 months ago 39
Swift Question

performSegueWithIdentifier: unexpectedly found nil while unwrapping an Optional value

I wish to allow selecting a certain row whereby, an action outlined as below will occur:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

tableView.deselectRowAtIndexPath(indexPath, animated: true)

// Ensure controller knows which dataset to pull from,
// so detail view is correct
var friendChat: Friend!

friendChat = mappedFriends[indexPath.row]

// Now set the conditional cases: if a friend then chat, if user then friend request if not user then can invite them:
if(friendChat.statusSort == 2) {

var controller : IndividualChatController!


controller.friendChat? = friendChat
controller.senderId? = Global.sharedInstance.userID
controller.senderDisplayName? = Global.sharedInstance.userName

self.performSegueWithIdentifier("showIndividualChat",sender: controller)

} else
if (friendChat.statusSort == 1) {

print("Can invite to be friend")

} else if (friendChat.statusSort == 0) {

print("Invite to Feast")



However, during the assignment, of:

controller.friendChat? = friendChat
controller.senderId? = FeastGlobal.sharedInstance.userID
controller.senderDisplayName? = FeastGlobal.sharedInstance.userName

The error:
fatal error: unexpectedly found nil while unwrapping an Optional value

Why would this occur? How can this be alleviated?


You are declaring, but not assigning a value to the variable controller here:

var controller : IndividualChatController!

You are making a promise that it is not nil by setting the type to an implicitly unwrapped optional with the exclamation mark, i.e. IndividualChatController!

However, that promise is not kept, because no value is assigned to it and it is in fact nil at the time this code runs:

controller.friendChat? = friendChat

This is why you are getting the fatal error.

The fix would be to assign a value to the controller var when you declare it. For example:

var controller:IndividualChatController = IndividualChatController()