Created
February 2, 2016 13:36
-
-
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
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
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