Same optional value is sometimes nil and sometimes not

84 Views Asked by At

I have the following in my viewDidAppear:

override func viewDidAppear(_ animated: Bool) {
        // Get the index based off of which tableview cell was selected in the last VC
        let selectedRecipeIndex = recipe.firstIndex(where: {$0.docID == passedDocID})

        // Get the appropriate data based off of the index determined above
        let currentRecipe = recipe[selectedRecipeIndex!]
        titleLabel.text = currentRecipe.title
    }

I'll sometimes get the following error on selectedRecipeIndex!: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

This error is very inconsistent. For the same index/cell, it will return a value but then if I open the app a separate time and tap the same index/cell it might return nil. It's seemingly random.

Why could the same index/cell sometimes return the value but sometimes return nil? And if it returns nil, what can I do to keep trying to call the value until it is not nil?

1

There are 1 best solutions below

2
pietrorea On

Try something like this:

override func viewDidAppear(_ animated: Bool) {
   super.viewDidAppear(animated)
   guard let selectedRecipeIndex = recipe.firstIndex(where: {$0.docID == passedDocID}) else {
       debugPrint("No index found.") // Add your own error handling
       return
   }
   let currentRecipe = recipe[selectedRecipeIndex]
   titleLabel.text = currentRecipe.title
}

You were crashing at the selectedRecipeIndex!, which you can fix with a guard-let or if-let. If there's a situation where there's an index, but it doesn't match up to the size of the recipe array, you can also add separate handling for that so you don't crash there.