Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - Prepare Segue

Tags:

ios

swift

swift3

I have 3 scenes in my storyboard. My initial View Controller is a Navigation Controller, then there is a relationship root view controller to a UI ViewController (view controller a) and then I have a push segue from a button in the ViewController to the third ViewController (view controller b) in the scene. I have given the push segue an identifier. Now I am trying to prepare my segue in the 2nd view controller (view controller a) like so:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "HistorySegue" {
            if let viewController = segue.destination as? HistoryController {
                viewController.detailItem = barcodeInt as AnyObject
            }
        }
    }

However when I run this code and push the button in controller a I get the following error:

fatal error: attempt to bridge an implicitly unwrapped optional containing nil

What am I doing wrong?

like image 685
user979331 Avatar asked Dec 24 '22 23:12

user979331


2 Answers

Replace your code with the following, it will not crash at least.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "HistorySegue" {
            if let viewController = segue.destination as? HistoryController {
              if(barcodeInt != nil){
                viewController.detailItem = barcodeInt as AnyObject
               }
            }
        }
    }
like image 174
User511 Avatar answered Jan 06 '23 09:01

User511


It must be that barcodeInt is defined as an implicitly unwrapped optional, like:

var barcodeInt:Int!

In that case, if it is nil when assigning it to detailItem, because of the !, swift takes your word for it that there is a non-nil value in there and dereferences it. That's a runtime error. Your best bet is to avoid ! in code you write (it's ok to leave the Apple generated code for IBOutlets, for example) if at all possible and learn more about optionals before going back to implicitly unwrapped optionals. And then, still use them sparingly.

Safer code for your situation:

if let viewController = segue.destination as? HistoryController, 
   let barcodeInt = barcodeInt as? AnyObject {

   viewController.detailItem = barcodeInt
} else {
   NSLog("Error: expected barcodeInt to be set") 
}
like image 27
Troy Avatar answered Jan 06 '23 07:01

Troy