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?
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
}
}
}
}
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With