Created
July 13, 2015 23:31
-
-
Save Ben-G/4a954bebce294d7235a8 to your computer and use it in GitHub Desktop.
Multicast Delegate Swift Prototype (WIP - currently storing strong references to delegates)
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
// 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