Synchronized 4.0.0

Synchronized 4.0.0

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Oct 2017
SwiftSwift Version 4.0
SPMSupports SPM

Maintained by James Ide.



  • By
  • James Ide



Exposes Objective-C's @synchronized directive to Swift. Like the Objective-C directive, Synchronized acquires a mutex lock, runs some code, and releases the lock when the code completes or throws an exception.

Linking the Framework

Once the framework is linked this Swift code should compile:

import Synchronized

let x = synchronized(NSObject()) { 0 }

Public API

public func synchronized(object: AnyObject, closure: () -> Void)

Usage:

synchronized(mutexObject) {
  // Code to run in your critical section
}

public func synchronized<T>(object: AnyObject, closure: () -> T) -> T

Usage:

let value = synchronized(threadUnsafeDictionary) {
  threadUnsafeDictionary[key]
}

Differences from @synchronized

Objective-C's @synchronized is a language-level directive and does not introduce a new function scope. This means that return statements cause the program to return from the surrounding function that contains the @synchronized directive.

- (void)returnDifferenceExample
{
    @synchronized {
        return;
    }
    NSLog(@"This line of code does not run.");
}

In contrast, Synchronized uses closures which do introduce a function scope. Returning from a closure passed to synchronized exits only the closure, not the surrounding function.

func returnDifferenceExample() {
    synchronized {
        return
    }
    println("This line of code does run.")
}

Synchronized's closures are annotated with the @noclosure attribute, which removes the need to access instance variables with self., so it is similar to Objective-C's @synchronized directive in this regard.