Skip to content

Instantly share code, notes, and snippets.

@diegosanchezr
Last active October 3, 2015 13:14
Show Gist options
  • Save diegosanchezr/a59a1eb5c4bf4da8ea30 to your computer and use it in GitHub Desktop.
Save diegosanchezr/a59a1eb5c4bf4da8ea30 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 where Self: AnyObject, ObserverType : AnyObject {
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)
}
public func removeObserver(observer : ObserverType) {
observers.removeObject(observer)
}
public func notifyObservers(notify : (ObserverType) -> ()) {
for observer in observers.allObjects {
notify(observer as! ObserverType)
}
}
}
public protocol SubjectObserver : class {
func subjectDidSomething()
}
public protocol Subject : Observable {
typealias ObserverType = SubjectObserver
}
public class ConcreteSubject : Subject {
public typealias ObserverType = ConcreteObserver // Otherwise doesn't compile, why? :(
public func doSomething() {
notifyObservers { (observer) -> () in
observer.subjectDidSomething()
}
}
}
public class ConcreteObserver : SubjectObserver {
public func subjectDidSomething() {
}
}
@diegosanchezr
Copy link
Author

Seems like compiler limitation. One solution:
https://gist.github.com/victorpimentel/1a963560d5183f887bca

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment