Last active
October 3, 2015 13:14
-
-
Save diegosanchezr/a59a1eb5c4bf4da8ea30 to your computer and use it in GitHub Desktop.
Observers swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seems like compiler limitation. One solution:
https://gist.github.com/victorpimentel/1a963560d5183f887bca