Skip to content

Instantly share code, notes, and snippets.

@gokselkoksal
Last active January 23, 2017 16:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gokselkoksal/317ed7b808b942d19800d5ed5f19aee3 to your computer and use it in GitHub Desktop.
Save gokselkoksal/317ed7b808b942d19800d5ed5f19aee3 to your computer and use it in GitHub Desktop.
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