Skip to content

Instantly share code, notes, and snippets.

@victorpimentel
Forked from diegosanchezr/Observer.swift
Last active October 3, 2015 13:01
Show Gist options
  • Save victorpimentel/1a963560d5183f887bca to your computer and use it in GitHub Desktop.
Save victorpimentel/1a963560d5183f887bca to your computer and use it in GitHub Desktop.
Observers swift
import Foundation
public protocol Observable : class {
typealias ObserverType
func addObserver(observer : ObserverType)
func removeObserver(observer : ObserverType)
}
let observersAssociatedKey = "observersKey"
extension Observable {
private var observers : NSHashTable {
get {
if let observers = objc_getAssociatedObject(self, observersAssociatedKey) as? NSHashTable {
return observers
} else {
let observers = NSHashTable.weakObjectsHashTable()
objc_setAssociatedObject(self, observersAssociatedKey, observers, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return observers
}
}
}
public func addObserver(observer : ObserverType) {
observers.addObject(observer as? AnyObject)
}
public func removeObserver(observer : ObserverType) {
observers.removeObject(observer as? AnyObject)
}
public func notifyObservers(notify : (ObserverType) -> ()) {
for observer in observers.allObjects {
notify(observer as! ObserverType)
}
}
}
public protocol SubjectObserver : AnyObject {
func subjectDidSomething()
}
public protocol Subject : Observable {
typealias ObserverType = SubjectObserver
}
public class ConcreteSubject : Subject {
public func doSomething() {
notifyObservers { (observer) -> () in
observer.subjectDidSomething()
}
}
}
public class ConcreteObserver : SubjectObserver {
public func subjectDidSomething() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment