Are Arrays thread-safe in Swift?

SPONSORED

glassfy-banner

Your in-app backend just got FREE ⚒️

Glassfy is the ultimate, free SDK for in-app monetization in Swift. Stay ahead with automatic store upgrades and manage subscriptions with ease. No more backend hassle, just revenue growth.

Learn More!
May 1, 2022 1 min readInterview

Introduction

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.​​

Eat. Sleep. Swift Anytime. Repeat.

Want latest weekly iOS updates?

Sign up for our newsletter.