Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save V8tr/3db48858a62ebc15796c032c8ff68b6f to your computer and use it in GitHub Desktop.
Save V8tr/3db48858a62ebc15796c032c8ff68b6f to your computer and use it in GitHub Desktop.
Atomic property in Swift using DispatchQueue and OperationQueue. See blog post for more details: http://www.vadimbulavin.com/atomic-properties/
// MARK: - DispatchQueue
class DispatchQueueAtomicProperty {
private let queue = DispatchQueue(label: "com.vadimbulavin.DispatchQueueAtomicProperty")
private var underlyingFoo = 0
var foo: Int {
get {
return queue.sync { underlyingFoo }
}
set {
queue.sync { [weak self] in
self?.underlyingFoo = newValue
}
}
}
}
// MARK: - OperationsQueue
class OperationsQueueAtomicProperty {
private let queue: OperationQueue = {
var q = OperationQueue()
q.maxConcurrentOperationCount = 1
return q
}()
private var underlyingFoo = 0
var foo: Int {
get {
var foo: Int!
execute(on: queue) { [underlyingFoo] in
foo = underlyingFoo
}
return foo
}
set {
execute(on: queue) { [weak self] in
self?.underlyingFoo = newValue
}
}
}
private func execute(on q: OperationQueue, block: @escaping () -> Void) {
let op = BlockOperation(block: block)
q.addOperation(op)
op.waitUntilFinished()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment