Last active
January 23, 2017 16:08
-
-
Save gokselkoksal/317ed7b808b942d19800d5ed5f19aee3 to your computer and use it in GitHub Desktop.
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
typealias Property<Value, ID> = GenericProperty<Value, ID, Void> | |
typealias CollectionProperty<Value, ID> = GenericProperty<Value, ID, CollectionChange> | |
struct GenericProperty<Value, ID, ChangeInfo> { | |
private var _value: Value | |
var value: Value { | |
get { return _value } | |
set { set(newValue) } | |
} | |
let id: ID | |
var onChange: ((ID, ChangeInfo?) -> Void)? | |
init(_ value: Value, _ id: ID, onChange: ((ID, ChangeInfo?) -> Void)? = nil) { | |
self._value = value | |
self.id = id | |
self.onChange = onChange | |
} | |
mutating func set(_ newValue: Value, info: ChangeInfo? = nil, silent: Bool = false) { | |
_value = newValue | |
if silent == false { | |
onChange?(id, info) | |
} | |
} | |
} | |
extension GenericProperty: CustomStringConvertible, CustomDebugStringConvertible { | |
var description: String { | |
return "{\(id) - \(value)}" | |
} | |
var debugDescription: String { | |
return description | |
} | |
} | |
infix operator << | |
infix operator <- | |
extension GenericProperty { | |
static func <<(lhs: inout GenericProperty<Value, ID, ChangeInfo>, rhs: Value) { | |
lhs.value = rhs | |
} | |
static func <<(lhs: inout GenericProperty<Value, ID, ChangeInfo>, rhs: (newValue: Value, info: ChangeInfo)) { | |
lhs.set(rhs.newValue, info: rhs.info) | |
} | |
// MARK: Silent | |
static func <-(lhs: inout GenericProperty<Value, ID, ChangeInfo>, rhs: Value) { | |
lhs.set(rhs, silent: true) | |
} | |
static func <-(lhs: inout GenericProperty<Value, ID, ChangeInfo>, rhs: (newValue: Value, info: ChangeInfo)) { | |
lhs.set(rhs.newValue, info: rhs.info, silent: true) | |
} | |
} | |
extension GenericProperty { | |
mutating func register(_ block: ((ID, Any?) -> Void)?) { | |
onChange = { block?($0, $1) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment