Skip to content

Instantly share code, notes, and snippets.

@IronLeash
Last active June 5, 2020 14:08
Show Gist options
  • Save IronLeash/024c066664e2ce91329658fb27997a71 to your computer and use it in GitHub Desktop.
Save IronLeash/024c066664e2ce91329658fb27997a71 to your computer and use it in GitHub Desktop.
MulticastDelegate
class MulticastDelegate<T> {
private let delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects()
func add(_ delegate: T) {
delegates.add(delegate as AnyObject)
}
func remove(_ delegateToRemove: T) {
for delegate in delegates.allObjects.reversed() {
if delegate === delegateToRemove as AnyObject {
delegates.remove(delegate)
}
}
}
func invoke(_ invocation: (T) -> Void) {
for delegate in delegates.allObjects.reversed() {
invocation(delegate as! T)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment