Swift: How to iterate through all elements in an Array, Set or Dictionary

Looping through all elements in Arrays, Sets and Dictionaries is fairly straightforward in Swift: we can use Fast Enumeration using a for-in loop. Here are three quick examples to demonstrate this.

I’ve also included how to access one specific element in either collection.

Arrays

Sets

Just as a reminder: a Set is more or less the same as an Array, with the exception that this collection has no order. Whilst iterating over an Array will always show the first item first, the order of a Set is unpredictable. Fetching a Set is slightly faster than an Array.

Dictionaries

Compared to Objective-C

To achieve the same thing in Objective-C, a bit more code is necessary. Just to remind ourselves, here’s how to iterate through an NSArray:

Likewise, here’s how Fast Enumeration works for an NSDictionary:

And of course for NSSets too:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.