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?
2
Answers
When you look at the documentation of the insert function, it says the following about the
i
parameter: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 printindex
,i
and the array you are inserting it in to see what is exactly going on.Still a bit confusing, but I think I understand what you’re going for…
Suppose
count
is5
…If it is 10 o’clock, you want an array result of:
If it is 15 o’clock, you want an array result of:
If it is 22 o’clock, you want it to "wrap around" and get an array result of:
(your
self.parse24(theString: String(index))
may be formatting it a little different).If that’s the case, take a look at this:
Edit
It’s probably important that you understand why you were getting the
Array index is out of range
error.You still didn’t post the code that was causing the error, but I’m guessing it is something like this:
So, if we start at 22 o’clock, and
count
equals5
, your code does this:You get the out of range error because you didn’t insert the empty string at [2], but
i
keeps incrementing.