arraysswiftindexoutofrangeexception

Swift 5: Why the Index out of range error appears?


I have two arrays that I am going to include in an array with object instances. When I try to do this, I get an error that the Index is out of range.

My code is below. I can't figure out why I'm getting this error. Can someone please let me know what I'm doing wrong?

import UIKit

let mealName = ["Breakfast", "Lunch", "Dinner", "Breakfast", "Lunch", "Dinner", "Breakfast", "Lunch", "Dinner", "Snack", "Supper", "Snack", "Breakfast", "Snack", "Lunch", "Dinner", "Supper", "Snack", "Breakfast", "Snack", "Dinner", "Snack", "Snack", "Snack", "Breakfast", "Snack", "Lunch", "Snack", "Snack", "Snack", "Breakfast", "Snack", "Lunch", "Snack", "Snack", "Snack", "Snack"]

let mealCalories = [725.03, 539.44, 849.49, 956.53, 267.18, 567.17, 353.47, 387.12, 700.76, 62.87, 857.35, 176.56, 123.79, 16.74, 813.74, 858.23, 127.26, 448.19, 932.62, 60.22, 880.55, 58.85, 78.48, 21.5, 564.74, 190.75, 911.01, 67.47, 81.44, 25.35, 954.94, 45.75, 858.71, 61.7, 189.75, 72.54, 75.84]


struct Meal {
    var mealName: String
    var mealCalories: Double
}

var meals = [Meal]()

for i in 0..<37 {
    meals[i].mealName = mealName[i]
    meals[i].mealCalories = mealCalories[i]
}

enter image description here


Solution

  • You have initialized the meals array but it is empty and doesn't have length. Therefore, when you refer to meals[i] it raises an error. You can do something like this:

    var meals: [Meal] = [Meal](repeating: Meal(mealName: "", mealCalories: 0.0), count: 37)
    
    

    Then you can refer to meals[i] (0<= i <37).

    If you want to start with an empty array you can add elements to it:

    var meals = [Meal]()
    

    Then:

    for i in 0..<37 {
        let meal = Meal(mealName: mealName[i], mealCalories: mealCalories[i])
        meals.append(meal)
    }
    

    In this case, the length of meals will grow as i grows.