Created
October 5, 2018 00:20
-
-
Save nanoxd/1983211617233e28ea34bbf433ca4f05 to your computer and use it in GitHub Desktop.
[MulticastDelegate] #swift Utility Class that can hold on to any number of delegates and invoke arbitrary blocks of code on them
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
/// Utility Class that can hold on to any number of delegates and invoke arbitrary blocks of code on them | |
public class MulticastDelegate<T: AnyObject> { | |
/// HashTable containing any number of delegates, held weakly | |
private let delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects() | |
/// Adds delegate to list of delegates | |
/// | |
/// - Parameter delegate: Delegate to add to list of known delegates | |
public func add(_ delegate: T) { | |
delegates.add(delegate as AnyObject) | |
} | |
/// Removes last known delegate from list of delegates | |
/// | |
/// - Parameter delegate: Delegate to remove from list | |
public func remove(delegate: T) { | |
for d in delegates.allObjects.reversed() { | |
if d === delegate as AnyObject { | |
delegates.remove(d) | |
} | |
} | |
} | |
/// Invokes closures on each of the known delegates | |
/// | |
/// - Parameter invocation: Closure containing code | |
public 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