Ever need to reverse the characters in a String or indices in a for loop? You can use ReversedCollection for that.
Here is a quick example for using reversed on a String.
You can also store the newly reversed String into another variable:
Looping through indices and their reversed indices is very easy as shown below.
The great thing about reversed is that you do not create new storage. You can also transform the reversed elements in a collection and get back a new array:
Here is one more example of enumerating the indices along with the reversed elements in an array:
From Apple’s documentation:
The reversed() method is always lazy when applied to a collection with bidirectional indices, but does not implicitly confer laziness on algorithms applied to its result. In other words, for ordinary collections c having bidirectional indices:
- c.reversed() does not create new storage
- c.reversed().map(f) maps eagerly and returns a new array
- c.lazy.reversed().map(f) maps lazily and returns a LazyMapCollection
Where to go from here?
You can check out Apple’s API on Reversed Collection for more information.