Created
September 5, 2021 09:41
-
-
Save yakushevichsv/0daded69d1b2c0c45a0aa0aec7809d99 to your computer and use it in GitHub Desktop.
Atomic Property Wrapper Using Unfair Lock
This file contains 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
// MARK: - Atomic | |
@propertyWrapper struct Atomic<T> { | |
private let lock = UnfairLock() | |
private var value: T | |
var wrappedValue: T { | |
get { | |
lock.lock() | |
defer { | |
lock.unlock() | |
} | |
return value | |
} | |
mutating set { | |
lock.lock() | |
defer { | |
lock.unlock() | |
} | |
value = newValue | |
} | |
} | |
init(wrappedValue: T) { | |
self.value = wrappedValue | |
} | |
mutating func adjust(block: @escaping ( _ value: T) -> T) { | |
lock.lock() | |
defer { | |
lock.unlock() | |
} | |
value = block(value) | |
} | |
} | |
// MARK: - Atomic.Bool | |
extension Atomic where T == Bool { | |
mutating func toggle() { | |
adjust { $0.toggle() } | |
} | |
} | |
//@Atomic var value = false | |
//_value.toggle() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment