Swift Thread-Safe Arrays

Be careful! This applies to value types!

Image for post
Image for post
Photo by amirali mirhashemian on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.7, and Swift 5.2.4



Array: An ordered series of objects which are the same type
Concurrency: means that two tasks can start, run and complete in overlapping time periods
Parallelism: is about performing work at the same time

The motivation

Concurrency is a big part of programming, and this article covers where you may actually encounter this in your day-to-day work as an iOS programmer.

Since many devices (including iOS devices) embrace the principles of parallelism (that is, executing on many threads at the same time).

Image for post
Image for post

There is a special type of problem in Computer Science — The Readers-Writers problem.

Because there are multiple threads, one thread may be reading a shared resource (in this case an Array) while another thread writes the same resource.

Here lies disaster!

Since Arrays are Value types but this doesn’t help in preventing the Readers-Writers problem.

This sucks.

Warning: The following code is not thread-safe (by definition — that is the point). This means that the code can and will crash at times because the code is simultaneously reading and writing at the same location — this is the point.

We set up an array (I’ve called it Array due to creativity issues).

Expected output:


Actual output: A crash, or all sorts of variations where we have corrupted data and:

- the output does, or does not have 6 elements

This is trash! We must fix this!

Note: The contents of the actual array can still be messed up bad, but this is not particuarly relevant to this example.

We place Swift’s Dispatch Barrier to allow concurrent reads while blocking write.

This particular solution is not generic, as this is not a prerequisite of this article!

Note: The contents of the actual array can still be messed up bad, but this is not particularly relevant to this example.


You need to be careful even with value types when in a multi-threaded environment. This article has given a rather brief introduction and I hope you’ve enjoyed it.

If you’ve any questions, comments or suggestions please hit me up on Twitter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store