Skip to content

Instantly share code, notes, and snippets.

@nvh
Created February 2, 2016 13:36
Show Gist options
  • Save nvh/056d0f0787616743c51d to your computer and use it in GitHub Desktop.
Save nvh/056d0f0787616743c51d to your computer and use it in GitHub Desktop.
An example how to have a synchronised property in a protocol-oriented way
public protocol SynchronizedValueContaining: class {
typealias SynchronizedValueType
var _valueAccessorSerialQueue: dispatch_queue_t { get }
var _privateValue: SynchronizedValueType { get set }
}
public extension SynchronizedValueContaining {
var synchronizedValue: SynchronizedValueType {
get {
var v: SynchronizedValueType!
dispatch_sync(_valueAccessorSerialQueue) {
v = self._privateValue
}
return v
}
set {
dispatch_async(_valueAccessorSerialQueue) {
self._privateValue = newValue
}
}
}
}
public extension SynchronizedValueContaining where SynchronizedValueType == Bool {
func synchronizedCheckAndEnableFlag() -> Bool {
var enabled: Bool!
dispatch_sync(_valueAccessorSerialQueue) {
enabled = !self._privateValue
if enabled! {
self._privateValue = true
}
}
return enabled
}
}
public extension SynchronizedValueContaining where SynchronizedValueType: _ArrayType {
func synchronizedAppendValue(value: SynchronizedValueType.Generator.Element) {
dispatch_sync(_valueAccessorSerialQueue) {
self._privateValue.append(value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment