Created
June 22, 2017 12:16
-
-
Save klemenzagar91/8c918dc20f6c8f648b6e68e6a86fa0da to your computer and use it in GitHub Desktop.
Multicast Delegate with hash table
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
class MulticastDelegate <T> { | |
private let delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects() | |
func add(delegate: T) { | |
delegates.add(delegate as AnyObject) | |
} | |
func remove(delegate: T) { | |
for oneDelegate in delegates.allObjects.reversed() { | |
if oneDelegate === delegate as AnyObject { | |
delegates.remove(oneDelegate) | |
} | |
} | |
} | |
func invoke(invocation: (T) -> ()) { | |
for delegate in delegates.allObjects.reversed() { | |
invocation(delegate as! T) | |
} | |
} | |
} | |
func += <T: AnyObject> (left: MulticastDelegate<T>, right: T) { | |
left.add(delegate: right) | |
} | |
func -= <T: AnyObject> (left: MulticastDelegate<T>, right: T) { | |
left.remove(delegate: right) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment