Last active
July 14, 2018 07:14
-
-
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/
This file contains hidden or 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: - 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