0

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

1
  • What exactly are you trying to do? You can iterative backwards with for index in (hourFormattingPattern.startIndex ..< hourFormattingPattern.endIndex).reverse() { } Commented Jul 7, 2016 at 2:34

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.