Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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