Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good way to iterate backwards through the Characters of a String?

Tags:

swift

What's the most Swiftian way to iterate backwards through the Characters in a String? i.e. like for ch in str, only in reverse?

I think I must be missing something obvious, because the best I could come up with just now was:

    for var index = str.endIndex; 
            index != str.startIndex; 
            index = index.predecessor() {
        let ch = str[index.predecessor()]
        ...
    }

I realise "what's the best..." may be classed as subjective; I suppose what I'm really looking for is a terse yet readable way of doing this.

Edit: While reverse() works and is terse, it looks like this might be quite inefficient compared to the above, i.e. it seems like it's not actually iterating backwards, but creating a full reverse copy of the characters in the String. This would be much worse than my original if, say, you were looking for something that was usually a few characters from the end of a 10,000-character String. I'm therefore leaving this question open for a bit to attract other approaches.

like image 343
Matt Gibson Avatar asked Aug 10 '14 09:08

Matt Gibson


1 Answers

The reversed function reverses a C: CollectionType and returns a ReversedCollection:

for char in "string".characters.reversed() {
  // ...
}

If you find that reversed pre-reverses the string, try:

for char in "string".characters.lazy.reversed() {
  // ...
}

lazy returns a lazily evaluated sequence (LazyBidirectionalCollection) then reversed() returns another LazyBidirectionalCollection that is visited in reverse.

like image 81
pNre Avatar answered Oct 24 '22 04:10

pNre