Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. typealias Property<Value, ID> = GenericProperty<Value, ID, Void>
  2. typealias CollectionProperty<Value, ID> = GenericProperty<Value, ID, CollectionChange>
  3.  
  4. struct GenericProperty<Value, ID, ChangeInfo> {
  5.  
  6. private var _value: Value
  7. var value: Value {
  8. get { return _value }
  9. set { set(newValue) }
  10. }
  11. let id: ID
  12. var onChange: ((ID, ChangeInfo?) -> Void)?
  13.  
  14. init(_ value: Value, _ id: ID, onChange: ((ID, ChangeInfo?) -> Void)? = nil) {
  15. self._value = value
  16. self.id = id
  17. self.onChange = onChange
  18. }
  19.  
  20. mutating func set(_ newValue: Value, info: ChangeInfo? = nil, silent: Bool = false) {
  21. _value = newValue
  22. if silent == false {
  23. onChange?(id, info)
  24. }
  25. }
  26. }
  27. extension GenericProperty: CustomStringConvertible, CustomDebugStringConvertible {
  28. var description: String {
  29. return "{\(id) - \(value)}"
  30. }
  31. var debugDescription: String {
  32. return description
  33. }
  34. }
  35.  
  36. infix operator <<
  37. infix operator <-
  38.  
  39. extension GenericProperty {
  40.  
  41. static func <<(lhs: inout GenericProperty<Value, ID, ChangeInfo>, rhs: Value) {
  42. lhs.value = rhs
  43. }
  44.  
  45. static func <<(lhs: inout GenericProperty<Value, ID, ChangeInfo>, rhs: (newValue: Value, info: ChangeInfo)) {
  46. lhs.set(rhs.newValue, info: rhs.info)
  47. }
  48.  
  49. // MARK: Silent
  50.  
  51. static func <-(lhs: inout GenericProperty<Value, ID, ChangeInfo>, rhs: Value) {
  52. lhs.set(rhs, silent: true)
  53. }
  54.  
  55. static func <-(lhs: inout GenericProperty<Value, ID, ChangeInfo>, rhs: (newValue: Value, info: ChangeInfo)) {
  56. lhs.set(rhs.newValue, info: rhs.info, silent: true)
  57. }
  58. }
  59.  
  60. extension GenericProperty {
  61. mutating func register(_ block: ((ID, Any?) -> Void)?) {
  62. onChange = { block?($0, $1) }
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement