How to loop through Set, Array and Dictionary in Swift

Hands up who loves Swift 🙌

Ok now that’s over, let’s take a look at the several ways we can loop through a Set, Array and a Dictionary in Swift. The approach you choose can be personal preference, related to the type of thing you’re doing, or perhaps the general code style of the application you’re working on.

Array

All of the below loops essentially do the same thing. The result is that they print the contents of “array” to the console in the expected order, i.e. “1”, “2”, “3”. Array’s are normally used when you’re working with ordered collections of elements.

Set

A Set is a collection of unordered unique elements. You mainly use a Set in 3 conditions:

  1. When you want to test an element exists in an efficient manner.
  2. If you’re not bothered about the order of elements.
  3. You need to ensure that an element only appears once in a collection.

It’s important to be aware of these things as looping through a Set will not output elements in the same way as it does with an array. You can create a Set with any element that implements the Hashable protocol. In the examples below, we create a Set from and Array of Strings.

If you like, you could extend Set to make getting elements by an Integer “index” a bit easier:

Dictionary

A Dictionary is a collection whose elements are key-value pairs. To get a value from a Dictionary, you must do so by providing a Key. The Key must be a Hashable type such as a String or Number.

The general approach to looping through a Dictionary is similar to a Set. Because the elements are key-value pairs, their order is not relevant and as such, accessing them via a loop may not always give you the output you expect.