Swift: Array Iteration with Index

When iterating over an array, it is very common to need the index of the objects in the array. In other programming languages, iterating over an array with index looks something like this:

Swift Iteration Part 1

Or if you’re familiar with a half-range operators from a language like Ruby, you might write something like this in Swift:

Swift Half Range

In Objective-C, I used to love using the NSArray’s enumerateObjectsUsingBlock: method for this purpose:

Objective-C Enumeration

It is time to forget all of these old habits! Swift has a really nice enumerate function built in for exactly this use-case that I now can’t live without:

Enumerate Swift


Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.

  • Ivan Schuetz

    This is quite cool

  • Abizer Nasir

    Aaargh! the plural of “dwarf” is “dwarves”!

  • Siarhei Brazil

    There should be some function as map , for enumerating items

  • Srinivas Malyala

    Even I am a huge fan of using enumerateObjectsUsingBlock in objective-c. I miss that, found this article very helpful. Thanks

  • This kind of trick is weirdly hard to find in official docs! Thanks! =)

  • * changed to `dwarfs.enumerate()` in Swift 2

    • Tony Kambourakis

      Awesome. Thanks, Luciano.

      • Mark Lucking

        Yes, THANKS!

    • Jose

      and `dwarfs.enumerated()` in Swift 3

  • I really like [1,2,3].forEach{print($0)}://Output: 1,2,3