Latest 1.0.1
Homepage https://github.com/jedlewison/SwiftSynchronized
License MIT
Platforms ios 8.0, osx 10.10, tvos 9.0, watchos 2.0, requires ARC
Authors

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.

Usage: Executing a critical section of code

Using synchronized:

synchronized(self) {
    // Critical section
}

Using NSLock and NSRecursiveLock:

lock.performAndWait {
    // Critical section
}

Usage: Returning/setting value

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) }
}

Installation

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.

Caution

Unlike Objective-C’s @synchronized, Swift synchronized does not handle exceptions.

Changes

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

Latest podspec

{
    "name": "SwiftSynchronized",
    "version": "1.0.1",
    "summary": "Objective-C's @synchronized for Swift, plus performAndWait for NSLock and NSRecursiveLock",
    "description": "@synchronized for Swift, using calls to the Objective-C runtime and providing nearly identical syntax. Also provides performAndWait extension for NSLock and NSRecursiveLock.",
    "homepage": "https://github.com/jedlewison/SwiftSynchronized",
    "license": "MIT",
    "authors": {
        "Jed Lewison": "[email protected]"
    },
    "source": {
        "git": "https://github.com/jedlewison/SwiftSynchronized.git",
        "tag": "1.0.1"
    },
    "platforms": {
        "ios": "8.0",
        "osx": "10.10",
        "tvos": "9.0",
        "watchos": "2.0"
    },
    "requires_arc": true,
    "source_files": "SwiftSynchronized.{swift,h}"
}

Pin It on Pinterest

Share This