Last active
August 18, 2020 08:04
-
-
Save achernoprudov/fece926d8198e1b27b5b1481fbee1291 to your computer and use it in GitHub Desktop.
Property wrapper for atomic modifications
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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