-
-
Save victorpimentel/1a963560d5183f887bca 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 { | |
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