Search code examples
swiftuipickerviewswift4uivewcontroller

How can I catch a nil error when trying to select a row in a UIPickerView?


Apparently, if you try to get an element out of a UIPickerView in viewWillAppear the first time a view is run, the app will crash with a returned nil error.

If I comment out the the following line and run the app, all works fine. Then I uncomment out the following line and run again, it works fine and continues to work fine.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    myPicker.selectRow(0, inComponent: 0, animated: true)
}

I have no idea what the difference is. Maybe there is something else going on in the app. Is there a way to catch that initial nil and just swallow it? It would mimic the first access of the view and having the code commented out. After the first access of the view, nil won't be returned.


Solution

  • If the picker is declared as implicit unwrapped optional by default just optional chain it:

    myPicker?.selectRow(0, inComponent: 0, animated: true)