Created
July 14, 2014 23:00
-
-
Save endocrimes/c250f4ce99a2bbb647cb to your computer and use it in GitHub Desktop.
A simple implementation of Observables in Swift
This file contains hidden or 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
struct Observable<T> { | |
typealias Observer = (send:(newValue: T) -> ()) | |
var observers = Dictionary<String, Observer>() | |
var value: T { | |
didSet { | |
_notify() | |
} | |
} | |
/** | |
* Create a new Observable with a stored value | |
*/ | |
init(_ value: T) { | |
self.value = value | |
} | |
/** | |
* Get the value stored instide the `Observable`. | |
* | |
* @return The value stored inside the observer. | |
*/ | |
func get() -> T { | |
return value | |
} | |
/** | |
* Update the stored value of the `Observable` and notify the observers. | |
* | |
* @param value A new value of type T | |
*/ | |
mutating func set(value: T) { | |
self.value = value | |
} | |
/** | |
* Add an observer with a random identifier | |
* | |
* @param observer A closure that takes a paramater of type T | |
* | |
* @return The identifier of the observer | |
*/ | |
mutating func addObserver(observer: Observer) -> String { | |
var identifier = _randomIdentifier() | |
addObserver(identifier, observer: observer) | |
return identifier | |
} | |
/** | |
* Add an observer with a given identifier | |
* | |
* @param identifier The identifier to register an observer for | |
* @param observer A closure that takes a paramater of type T | |
*/ | |
mutating func addObserver(identifier: String, observer: Observer) { | |
observers[identifier] = observer | |
} | |
/** | |
* Remove an Observer with a given identifier | |
* | |
* @param identifier the Observer to remove an identifier for | |
*/ | |
mutating func removeObserver(identifer: String) { | |
observers.removeValueForKey(identifer) | |
} | |
// Private | |
func _notify() { | |
for (identifier, observer) in observers { | |
observer.send(newValue: value) | |
} | |
} | |
func _randomIdentifier() -> String { | |
var tempString = "" | |
for index in (0 ..< 30) { | |
tempString += String(arc4random_uniform(10)) | |
} | |
return tempString | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment