Data Structures in Swift — Array vs Dictionary

Ta DUONG NGOC
3 min readMar 31, 2022

Let review some traits of two of Swift’s data structures: Array and Dictionary.

Array

An array is a general-purpose generic collection that stores elements in an order. Generic in this case means the elements in an array can be any type.

When you are considering any data structure, there are some specific capabilities to be aware of:

  1. Is the data structure ordered? How is it ordered?

Elements in an array are explicitly ordered. Array use zero-based index system to maintain that order. store one element at each index and allow you to access elements at any given index.

2. There are other aspects of performance you should consider like how does the data structure handle adding or removing data?

With arrays, there are 2 factors at play:

First, where are you trying to insert or remove an element?
Remember, array use zero-based index system, so if you try to add something new at the front of the array, every element in array needs to shift over one index.
You should have the same problem if you try to remove the first element. Both of those should be Linear Time Operations (O(n))

If you trying to add something new to the end of an array, it should be Constant Time Operation no matter how large the array is.

The other factor is capacity.
Does the array have enough space to add something new?
Behind the scenes, arrays are given a predetermined amount of space to store their elements. If you try to add an element to a full array, all of the contents are copied in to a new larger container in memory. That can be a costly operation. So each time the array needs to add more memory, it doubles in capacity.
In Swift, the answer for the question “Does the array have enough space to add something new?” is usually YES.
Overall, capacity doesn’t affect the performances on arrays.

Dictionary

Dictionary is the collections of key-value pairs.
Unlike array, dictionaries aren’t explicitly order. If you add a new element to dictionary, you have no idea where it will be added.

The insertion and lookup in Dictionary is Constant Time (O(1)). That is the benefit of Dictionary in comparation with Array.

Choosing a data structure

There is no best data structure. Only better choices for the specific problem you are trying to solve.

Reference from Raywenderlich course.

--

--

Ta DUONG NGOC

Senior iOS developer, Mobile Project Leader, Project Manager