Swift 3 - Prepare Segue

前端 未结 3 2129
终归单人心
终归单人心 2021-01-14 00:06

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 contr

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 00:32

    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") 
    }
    

提交回复
热议问题