Skip to content

Instantly share code, notes, and snippets.

@orchetect
Last active October 20, 2021 02:42
Show Gist options
  • Save orchetect/0ce6c41193297acc67003e9a04659c90 to your computer and use it in GitHub Desktop.
Save orchetect/0ce6c41193297acc67003e9a04659c90 to your computer and use it in GitHub Desktop.
Swift 5 propertyWrapper that wraps a value with a semaphore to prevent overlapping access.
/// Wraps a value with a DispatchSemaphore(value: 1) to prevent overlapping access.
@propertyWrapper public struct Semaphored<T> {
private var value: T
private var semaphore = DispatchSemaphore(value: 1)
public var wrappedValue: T {
get {
defer { semaphore.signal() }
semaphore.wait()
return value
}
_modify {
semaphore.wait()
yield &value
semaphore.signal()
}
}
public init(wrappedValue: T) {
self.value = wrappedValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment