Still a bit confusing, but I think I understand what you're going for...
Suppose count is 5 ...
If it is 10 o'clock, you want an array result of:
[10:00 to 11:00]
[11:00 to 12:00]
[12:00 to 13:00]
[13:00 to 14:00]
[14:00 to 15:00]
If it is 15 o'clock, you want an array result of:
[15:00 to 16:00]
[16:00 to 17:00]
[17:00 to 18:00]
[18:00 to 19:00]
[19:00 to 20:00]
If it is 22 o'clock, you want it to "wrap around" and get an array result of:
[22:00 to 23:00]
[23:00 to 0:00]
[0:00 to 1:00]
[1:00 to 2:00]
[2:00 to 3:00]
(your self.parse24(theString: String(index)) may be formatting it a little different).
If that's the case, take a look at this:
var tempArray: Array<String> = []
// no need for an "i" counter variable
for _ in 0..<self.count {
var theHours = ""
// if we're at 24, set index to 0
if (index == 24) {
index = 0
}
if (index == 23) {
// if we're at 23, the string will be "23:00 to 0:00"
theHours = "23:00 to 0:00"
} else {
// the string will be "index to index+1"
theHours = "\(index):00 to \(index+1):00"
}
// don't use insert, just append the new string
//tempArray.insert(theHours, at: i)
tempArray.append(theHours)
index = index + 1
}
self.timeArray = tempArray
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:
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))
}
if theHours.isEmpty {
// don't add the empty string to the array
} else {
// add it to the array
tempArray.insert(theHours, at: i)
}
index = index + 1
}
So, if we start at 22 o'clock, and count equals 5, your code does this:
i equals 0
index equals 22
theHours = "22 to 23"
insert string at [i] // i is 0
increment index
increment i
i now equals 1
index now equals 23
theHours = "23 to 0"
insert string at [i] // i is 1
increment index
increment i
i now equals 2
index now equals 24
set index to 0
theHours = ""
DON'T insert empty string
increment i
i now equals 3
index now equals 0
theHours = "0 to 1"
insert string at [i] // i is 3
*** ERROR ***
You get the out of range error because you didn't insert the empty string at [2], but i keeps incrementing.