What is the Swift equivalent to Objective-C's "@synchronized"?

Bill picture Bill · Jun 4, 2014 · Viewed 111.9k times · Source

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

Answer

Bryan McLemore picture Bryan McLemore · Jun 8, 2014

I was looking for this myself and came to the conclusion there's no native construct inside of swift for this yet.

I did make up this small helper function based on some of the code I've seen from Matt Bridges and others.

func synced(_ lock: Any, closure: () -> ()) {
    objc_sync_enter(lock)
    closure()
    objc_sync_exit(lock)
}

Usage is pretty straight forward

synced(self) {
    println("This is a synchronized closure")
}

There is one problem I've found with this. Passing in an array as the lock argument seems to cause a very obtuse compiler error at this point. Otherwise though it seems to work as desired.

Bitcast requires both operands to be pointer or neither
  %26 = bitcast i64 %25 to %objc_object*, !dbg !378
LLVM ERROR: Broken function found, compilation aborted!