Skip to content

Instantly share code, notes, and snippets.

@dagronf
Last active August 5, 2019 01:26
Show Gist options
  • Save dagronf/6a0e8cce9abf7ee38def0601dcabd387 to your computer and use it in GitHub Desktop.
Save dagronf/6a0e8cce9abf7ee38def0601dcabd387 to your computer and use it in GitHub Desktop.
// FROM: https://www.objc.io/blog/2018/12/18/atomic-variables/
final class Atomic<A> {
private let queue = DispatchQueue(label: "Atomic serial queue")
private var _value: A
init(_ value: A) {
self._value = value
}
var value: A {
get {
return queue.sync { self._value }
}
}
func mutate(_ transform: (inout A) -> ()) {
queue.sync {
transform(&self._value)
}
}
}
@dagronf
Copy link
Author

dagronf commented Dec 18, 2018

Use like :-

let x = Atomic<Int>(5)
x.mutate { $0 += 1 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment