Reverse Collection in Swift 4

tiptopgs profile image Jen Chang Originally published at Medium on ・1 min read

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.

Reversing 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.

Reversing indices

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:

Reversing numbers and transforming the results

Here is one more example of enumerating the indices along with the reversed elements in an array:

Enumerating list in reverse order

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.

Posted on by:

tiptopgs profile

Jen Chang


Senior iOS Engineer who loves to play ping pong at the moment.


markdown guide