Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading