Search code examples
iosswiftuipickerview

Why Is My Array Index Out Of Range Using An If Statement?


This is the code:

func setTimeArray() {
    let iStart = Int(Double(selectedStart)! * 0.01)
    var index = iStart
    var tempArray: Array<String> = []

    print("count is ", count)
    for i in 0..<self.count  {
        var theHours = ""
        if (index == 24) {
           index = 0
        }  else if (index == 23) {
            theHours = self.parse24(theString: String(index)) + " to " + self.parse24(theString: "0")
        } else {
            theHours = self.parse24(theString: String(index)) + " to " + self.parse24(theString: String(index + 1))
        }
        tempArray.insert(theHours, at: i)
        index = index + 1
    }
    self.timeArray = tempArray
}

This code works just fine, but I need to wrap the place where it inserts into the tempArray so that it doesn't add an empty string. Unfortunately, when I try to add an if statement, or place tempArray.insert(theHours, at: i) inside the already existing if statements, I get the error: "Swift/Array.swift:405: Fatal error: Array index is out of range"

I mean, I'm actually adding more items without the if statement! Can anyone tell me how to fix this?


Solution

  • When you look at the documentation of the insert function, it says the following about the i parameter:

    i

    The position at which to insert the new element. index must be a valid index of the array or equal to its endIndex property.

    You need to insert the element to an existing index or add it to the end of the array. It might help to add a print statement to print index, i and the array you are inserting it in to see what is exactly going on.