SwiftSynchronized provides synchronized, a global public function that serves as a Swift-substitute for Objective-C's @synchronized directive. It also adds a performAndWait
extension to NSLock and NSRecursiveLock.
Using synchronized:
synchronized(self) {
// Critical section
}
Using NSLock and NSRecursiveLock:
lock.performAndWait {
// Critical section
}
Using synchronized:
var _privateStorage: String // The actual private storage
var threadSafeAccessor: String { // A thread safe accessor
get { return synchronized(self, _privateStorage) }
set { synchronized(self, _privateStorage = newValue) }
}
Using NSLock and NSRecursiveLock:
let lock = NSLock() // Or NSRecursiveLock()
var _privateStorage: String // The actual private storage
var threadSafeAccessor: String { // A thread safe accessor
get { return lock.performAndWait(_privateStorage) }
set { lock.performAndWait(_privateStorage = newValue) }
}
To install via CocoaPods:
pod 'SwiftSynchronized'
Don't forget to:
import SwiftSynchronized
somewhere in your project.
You can also use Carthage, or simply add SwiftSynchronized.swift directly to your project.
Unlike Objective-C's @synchronized, Swift synchronized does not handle exceptions.
1.0.0 -- Added support for autoclosures which allows improved syntax for return values and extension for NSLock and NSRecursiveLock. Also added Carthage support and support for multiple platforms in CocoaPods. 0.0.1 -- Initial release