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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With