Swift – the Swift equivalent to Objective-C’s “@synchronized”

concurrencymutexswift

I've searched the Swift book, but can't find the Swift version of @synchronized. How do I do mutual exclusion in Swift?

Best Answer

You can use GCD. It is a little more verbose than @synchronized, but works as a replacement:

let serialQueue = DispatchQueue(label: "com.test.mySerialQueue")
serialQueue.sync {
    // code
}