Created
September 18, 2019 15:08
-
-
Save sgl0v/ec3748f8267e579de6093993f9dd1b77 to your computer and use it in GitHub Desktop.
Atomic property wrapper
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
| @propertyWrapper | |
| struct Atomic<Value> { | |
| private var value: Value | |
| private let lock = NSLock() | |
| init(wrappedValue value: Value) { | |
| self.value = value | |
| } | |
| var wrappedValue: Value { | |
| get { return load() } | |
| set { store(newValue: newValue) } | |
| } | |
| func load() -> Value { | |
| lock.lock() | |
| defer { lock.unlock() } | |
| return value | |
| } | |
| mutating func store(newValue: Value) { | |
| 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