Skip to content

Instantly share code, notes, and snippets.

@achernoprudov
Last active August 18, 2020 08:04
Show Gist options
  • Save achernoprudov/fece926d8198e1b27b5b1481fbee1291 to your computer and use it in GitHub Desktop.
Save achernoprudov/fece926d8198e1b27b5b1481fbee1291 to your computer and use it in GitHub Desktop.
Property wrapper for atomic modifications
/// Property wrapper for atomic modifications
@propertyWrapper
public struct Atomic<T> {
private var value: T
private let lock = NSLock()
public init(wrappedValue value: T) {
self.value = value
}
public var wrappedValue: T {
get {
return load()
}
set {
store(newValue: newValue)
}
}
func load() -> T {
lock.lock()
defer {
lock.unlock()
}
return value
}
mutating func store(newValue: T) {
lock.lock()
defer {
lock.unlock()
}
value = newValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment