Are Arrays thread-safe in Swift?

interview May 02, 2022
Are Arrays thread-safe in Swift?

An array is an ordered, random-access generic collection. The Array type to hold elements of a single type, the array’s Element type. An array can store any kind of elements—from integers to strings to classes.

Are Arrays Thread-Safe?

Intrinsically, Arrays in Swift are not thread-safe. Arrays are 'value-typed' in the effect of assignment, initialization, and argument passing — creates an independent instance with its own unique copy of its data.

Immutable arrays (declared using let) are thread-safe since it is read-only. But mutable arrays are not thread-safe. Many threads can read a mutable instance of an array simultaneously without an issue but it is unsafe to let one thread modify the array while another is reading it.

Conclusion

Mutable arrays are not thread safe but they can be implemented to be thread-safe. Array uses copy-on-write (arrays are copied before mutating). Dispatch barriers are a common method to use arrays across multiple threads:

let queue = DispatchQueue(label: "thread-safe-array")

// write
queue.async() {
    // perform writes on data
}

// read
queue.sync() {
    // perform read and assign value
}

We at Swift Anytime have the mission to make learn iOS development the way everyone enjoys it. You can check out our articles on SwiftUI, Swift, iOS Interview Questions and get started with your iOS journey today.​​

Signup now to get notified about our
FREE iOS Workshops!