Last active
July 15, 2024 15:09
-
-
Save Edudjr/7e24c8a5ad95fb9e1e28b7a81d2bbb39 to your computer and use it in GitHub Desktop.
Swift implementation of a thread-safe, generic, Property Wrapper
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
@propertyWrapper | |
final class ThreadSafe<T> { | |
private let queue = DispatchQueue(label: "ThreadSafeTypeQueue", | |
attributes: .concurrent) | |
private var content: T | |
var wrappedValue: T { | |
get { | |
queue.sync { | |
content | |
} | |
} | |
set { | |
queue.async(flags: .barrier) { [weak self] in | |
guard let self = self else { return } | |
self.content = newValue | |
} | |
} | |
} | |
init(wrappedValue: T) { | |
self.content = wrappedValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment