-2

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?

Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
amirbt17
  • 533
  • 1
  • 4
  • 13
  • Crash means that this array has no such element. You only can solve this by yourself using debugging. Add logs to see the content of the recipe before taking first index. – Phil Dukhov Sep 04 '21 at 17:33
  • 1
    Are you getting the recipes through some asynchronous call perhaps? Either way you should use `if let…` instead of force unwrapping – Joakim Danielson Sep 04 '21 at 17:35
  • Unrelated - it's best practice to call `super.ViewDidAppear(animated)` before doing anything in the method – pietrorea Sep 04 '21 at 17:42
  • 1
    Why pass the document id anyway if you are jus going to search for it? Why not pass the recipe itself? – Paulw11 Sep 04 '21 at 21:05
  • 1
    It's _your_ job to tell _us_ how this can be. Your code refers to an unknown: `recipe`. Until you tell us how that is populated and why you are so certain that it contains an element whose `docID` is `passedDocID` (and what _that_ is and how _it_ gets populated), this is all just hand-waving. – matt Sep 04 '21 at 23:44

1 Answers1

-1

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
pietrorea
  • 841
  • 6
  • 14