I have to diagree.
In Swift, Array, String, and Dictionary are all value types. They behave much like a simple int value in C, acting as a unique instance of that data. You don’t need to do anything special — such as making an explicit copy — to prevent other code from modifying that data behind your back. Importantly, you can safely pass copies of values across threads without synchronization. In the spirit of improving safety, this model will help you write more predictable code in Swift.
- Source: https://developer.apple.com/swift/blog/?id=10
The following code is thread-safe:
import Foundation
class SomeClass {
let lock = NSLock()
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
func getNumbers ( ) -> [Int] {
lock.lock()
let result = self.numbers
lock.unlock()
return result
}
func modifyNumbers ( ) {
lock.lock()
let first = self.numbers.removeFirst()
self.numbers.append(first)
lock.unlock()
}
}
let numberContainer = SomeClass()
let thread1 = Thread() {
while true {
var numbers = numberContainer.getNumbers()
// Numbers is now copy on write!
// Modifying it will copy it.
let first = numbers.removeFirst()
numbers.append(first)
}
}
thread1.start()
let thread2 = Thread() {
while true {
var numbers = numberContainer.getNumbers()
// Numbers is now copy on write!
// Modifying it will copy it.
let first = numbers.removeFirst()
numbers.append(first)
}
}
thread2.start()
while true {
numberContainer.modifyNumbers()
}
Three threads are constantly modifying a copy-on-write array and this causes no issues at all. Try it. Copy the code to test.swift:
swiftc -sanitize=thread test.swift && ./test
If this wasn't thread-safe, then Swift would not treat arrays as values types and they would not "behave much like a simple int value in C" since for int values in C the code above would also be thread-safe.
And in case you may think "Okay, then they must have changed that recently, this was definitely not the case when I wrote my reply", please note that the first blog post I linked is from Aug 15, 2014 and your reply is from Apr 14, 2017