Skip to content

Instantly share code, notes, and snippets.

@dagronf
Last active October 17, 2023 12:33
Show Gist options
  • Save dagronf/2d42b92272e692a7287bc1893e1bae65 to your computer and use it in GitHub Desktop.
Save dagronf/2d42b92272e692a7287bc1893e1bae65 to your computer and use it in GitHub Desktop.
Swift method to provide the equivalent of `@synchronised` from objc
/// Provide the equivalent of @synchronised on objc
private func synchronized<T>(_ lock: AnyObject, _ body: () throws -> T) rethrows -> T {
objc_sync_enter(lock)
defer { objc_sync_exit(lock) }
return try body()
}
/// Simple lockable class
class Lockable {
private var lockable: AnyObject
init(using lockable: AnyObject) {
self.lockable = lockable
}
func usingLock<Value>(_ body: () throws -> Value) rethrows -> Value {
objc_sync_enter(self.lockable)
defer { objc_sync_exit(self.lockable) }
return try body()
}
}
@dagronf
Copy link
Author

dagronf commented Aug 5, 2019

Usage :-

func remove(document: MyDocument) -> Bool {
    return synchronized(self) {
        RemoveDocument(self.index, document)
    }
}

func add(text: String) -> Void {
    synchronized(self) {
        AddDocumentWithText(self.index, text)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment