Reputation: 531
I have this code:
var formatterIndex = hourFormattingPattern.endIndex
let formattingPatternRange = formatterIndex ..< hourFormattingPattern.startIndex
But I'm getting an error of bad access when the second line is called. Is there a way to specify a range that reverses through the string hourFormattingPattern
? After the initialization, I'm doing this:
while !stop {
//Do pattern matching and switching with string and replace char string
formatterIndex = formatterIndex.predecessor()
if formatterIndex <= hourFormattingPattern.endIndex || tempIndex <= tempString.endIndex {
stop = true
}
}
Any help appreciated. Thank you
Upvotes: 0
Views: 275
Reputation: 14824
Yes, you can't form a range from a larger number to a smaller one. Also, endIndex
is not a valid index--it's one past the last valid index. You can, however, form your range forwards and then reverse it:
var formatterIndex = hourFormattingPattern.endIndex
let formattingPatternRange = hourFormattingPattern.startIndex..<formatterIndex
for formatterIndex in formattingPatternRange.reversed() where !stop {
//Do pattern matching and switching with string and replace char string
if formatterIndex <= hourFormattingPattern.endIndex || tempIndex <= tempString.endIndex {
stop = true
}
}
However, your logic may be off, because all possible values of formatterIndex
are <= hourFormattingPattern.endIndex
, and thus stop
will be set true
on the first run of your loop.
Upvotes: 2