Search code examples
iosswiftswitch-statementsegueuistoryboardsegue

Swift - Using Switch Statement in prepareForSegue method


I've setup the following switch statement, to handle 3 different button taps: rock, paper, scissors. Tapping on the Rock button for example, takes you to ResultViewController, with the "rockSegue" info showing.

Every time I run the app, and then tap on one of the buttons (rock for example), it then crashes when transitioning to the ResultViewController saying that the resultImage contains nil when unwrapping an optional value. The asset it's referencing definitely exists, so I'm a bit stuck as to what I've done wrong here?

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let controller = segue.destinationViewController as ResultViewController
    switch segue.identifier! {
    case "rockSegue":
        controller.resultImage!.image = UIImage(named: "PaperCoversRock")
        controller.resultLabel!.text = "You lose"...(continued)

The button contains the following code:

  @IBAction func rockButton() {
    performSegueWithIdentifier("rockSegue", sender: self)   
}

Solution

  • This line:

    controller.resultImage!.image = UIImage(named: "PaperCoversRock")
    

    Tries to force (due to '!') unwrapping of resultImage before assigning the generated UIImage to its image property.

    Since resultImage is a nil at that point you get the exception regardless if the image exists or not as it cannot be unwrapped for accessing its image property.

    resultImage must be initialized before running the line above

    UPDATE:

    At this point when you get the destination controller it is initialized but its outlets are still haven't be generated as the controller's view was not accessed yet (which triggers the viewDidLoad and the initialization of the outlets).

    So you can either :

    1. Store the image name as a property in the destination controller and set the image in the controller's viewDidLoad() method

    2. Access the controller's view (even just read it) it will trigger the controller's view creation flow (not so sure about this one though as I read somewhere that it is possible)