watchOS - Chapter 7 Tables - Bug (Index out of range)

Hi guys,

Are you aware that the recipes final project has a bug when you select the last row of the table “Curried chicken salad”?

It’s a “Index out of range”

Thoughts?

There is a problem with the number of rows after the add-function in RecipesController.swift. With this function called there is no correlation between the original array of the recipes, because of the added headers and the sorting into the different types. To fix this problem, I declared a new array "var chosenRecipe: [Recipe] = [] and in the add-function I appended the actual recipe to this array. In case of a header row I appended the first recipe as a dummy. The return statement of the contextForSegue function has to be changed to "return chosenRecipe[rowIndex]. That’s it. I don’t know, wether there is a better solution, but with my changes, it works fine now.

1 Like

I found that selecting any of the dinner recipes caused the index out range issue. Also, when selecting a recipe from the first screen, the instructions did not correspond to the selected recipe. I chose to create a dictionary that relates the tableRowIndex selected to the index of the recipe in recipeStore.recipes.

I added the following code at the end of awake(withContext:) in RecipesController:

	var sectionOffset = 1
	var tableRowIndex = 0

	for (_, recipes) in map {
		for recipe in recipes {
			for (index, originalRecipe) in self.recipeStore.recipes.enumerated() {
				if recipe.name == originalRecipe.name {
					let tableRow = tableRowIndex + sectionOffset
					self.recipeIndexForRow[tableRow] = index
					break
				}
			}
			tableRowIndex += 1
		}
		sectionOffset += 1
	}

Also in RecipesController I replaced the code in contextForSegue with

    return self.recipeStore.recipes[self.recipeIndexForRow[rowIndex]!]

Now selecting a row does not cause an index out of range error, and the correct recipe is shown.