Skip to content

Instantly share code, notes, and snippets.

@Edudjr
Last active July 15, 2024 15:09
Show Gist options
  • Save Edudjr/7e24c8a5ad95fb9e1e28b7a81d2bbb39 to your computer and use it in GitHub Desktop.
Save Edudjr/7e24c8a5ad95fb9e1e28b7a81d2bbb39 to your computer and use it in GitHub Desktop.
Swift implementation of a thread-safe, generic, Property Wrapper
@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