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.



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.


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:

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

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