lifewithelliott lifewithelliott - 10 months ago 43
Swift Question

Unwind segue interferring with a show segue

Background into what I am trying to achieve:

MainViewController presents TableVC.
I will tap on a cell to present a DetailVC.
With the ability to dismiss by a doneBarButton on the navigation bars on either TableVC or DetailVC.

All doneBarButton's are rooted to the MainViewController so i would think that no matter what the view controllers would dismiss to the MainViewController.

What I am experiencing is a crash upon tapping on my TableVC's doneBarButton but not on my DetailVC's doneBarButton. Because they are all rooted to the MainViewController through interface builder I did not think I should have to code anything in the TableVC's prepareForSegue method however the switch case for the identifier is being highlighted and the debug console outputs

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

I'm not entirely sure where to pinpoint what needs fixing, whether that be in the interface builder or including something in the prepareForSegue method.

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
switch segue.identifier! // Line highlighted with error in debug console
case "toDetailVC": // Properly presents detailVC through a cell being tapped


Answer Source

You haven't assigned an identifier to your unwind segue, so the property is nil. Since you are force unwrapping it with !, it crashes.

To fix the problem, find the unwind segue in the Document Outline view. Select it and then in the Attributes Inspector, give the segue an identifier.

Xcode interface showing unwind segue ID

Alternate Solution:

Since you probably don't care about the unwind identifier, you could also solve the problem by picking a safer way to unwrap the segue.identifier:

switch segue.identifier ?? "" {

This use of the nil coalescing operator ?? replaces the unassigned identifiers with the empty string.