Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
print("Swiftstub Running XCode 7.1 Swift 2")
typealias Item = String
enum ObserverAction {
case Update(items: [Item])
case Delete(items: [Item])
case Insert(items: [Item])
}
class Model {
// The observation closure
typealias Observer = (ObserverAction) -> ()
// Our internal Item storage
private var items: [Item] = []
// All our Storage-Observers
private var observers: [String: Observer] = [:]
func addItem(item: Item) {
items.append(item)
process(.Insert(items: [item]))
}
func removeItem(item: Item) {
...
process(.Delete(items: [item]))
}
func updateItem(item: Item, withItem newItem: Item) {
...
process(.Update(items: [newItem]))
}
// MARK: Observation
/**
Register an Observer
- parameter observer: The closure to call for all changes
- returns: The registration token
*/
func addObserver(observer: Observer) -> String {
let token = NSUUID().UUIDString
observers[token] = observer
}
func removeObserver(token: String) {
observers[token] = nil
}
private func process(change: ObserverAction) {
for (_, observer) in observers {
observer(change)
}
}
}
// Usage Example: Create a model
let model = Model()
// Add an observer: This closure will be called whenever the model is changed
model.addObserver(observer: { (action: ObserverAction) -> () in
switch action {
case .Insert(let items): print("Observer triggered, \(items.count) inserted")
default: ()
}
})
// Change the model, trigger an observation
model.addItem("Test")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment