Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Created July 13, 2015 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ben-G/4a954bebce294d7235a8 to your computer and use it in GitHub Desktop.
Save Ben-G/4a954bebce294d7235a8 to your computer and use it in GitHub Desktop.
Multicast Delegate Swift Prototype (WIP - currently storing strong references to delegates)
// Multicast delegate prototype. Better solution in Obj-C here: http://arielelkin.github.io/articles/objective-c-multicast-delegate/
// Implementations
class CarListener: Hashable {
var hashValue = Int(arc4random())
func receivedNoise(noiseEmitter: CarListenable) {
}
}
func ==(lhs: CarListener, rhs: CarListener) -> Bool {
return lhs === rhs
}
class CarListenable: Listenable {
var listeners: Set<CarListener>?
func something() {
if let listeners = listeners {
listeners.map { $0.receivedNoise(self) }
}
}
}
// Generic Protocol
protocol Listenable {
typealias Listener : Hashable
var listeners: Set<Listener>? { get set }
mutating func addListener(newListener: Listener)
mutating func removeListener(newListener: Listener)
}
extension Listenable {
mutating func addListener(newListener: Listener) {
// TODO: create weak reference here
listeners?.insert(newListener)
}
mutating func removeListener(listenerToRemove: Listener) {
// TODO: create weak reference here
listeners?.remove(listenerToRemove)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment