Sobes.tech
Junior — Middle

What prevents the safe use of collections in a multithreaded environment in Swift?

sobes.tech AI

Answer from AI

In Swift, standard collections (such as Array, Dictionary, Set) are not thread-safe. This means that concurrent access to the same collection from different threads without synchronization can lead to race conditions, data corruption, and unpredictable behavior.

Reasons:

  • Lack of built-in synchronization: collections do not use locks or other protection mechanisms when modified.
  • Modifying a collection during iteration from another thread can cause a crash.

To use them safely in a multithreaded environment, you need to provide synchronization yourself, for example, using:

  • DispatchQueue with barriers (barrier) for writing
  • NSLock or other locking primitives
  • Thread-safe wrappers or data structures

Example of using DispatchQueue for synchronizing access to an array:

class ThreadSafeArray<T> {
    private var array = [T]()
    private let queue = DispatchQueue(label: "com.example.threadSafeArray", attributes: .concurrent)

    func append(_ element: T) {
        queue.async(flags: .barrier) {
            self.array.append(element)
        }
    }

    func get(at index: Int) -> T? {
        var result: T?
        queue.sync {
            if array.indices.contains(index) {
                result = array[index]
            }
        }
        return result
    }
}