Created
March 3, 2015 04:26
-
-
Save chrishulbert/71828c1f9efbfd131e6d to your computer and use it in GitHub Desktop.
Swift implementation of C#-style Events concept (eg a manager with multiple weakly-referenced 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
import Foundation | |
/// Since there can be multiple delegates, they can only be used to signifying events (output), not for | |
/// supplying data for the manager (input). | |
@objc protocol MyManagerDelegate { | |
func manager(manager: MyManager, isNowLoading: Bool) | |
} | |
@objc class MyManager { | |
/// Multiple delegates. | |
let delegates = NSHashTable.weakObjectsHashTable() | |
// Add a delegate. | |
func addDelegate(delegate: MyManagerDelegate) { | |
delegates.addObject(delegate) | |
} | |
/// Example of how you'd call the multiple delegates. | |
private func tellDelegatesIsNowLoading(loading: Bool) { | |
for object in delegates.allObjects { | |
let delegate = object as MyManagerDelegate | |
delegate.manager(self, isNowLoading: loading) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Granted, KVO is often a good alternative to this. Unfortunately, KVO isn't a first-class member of Swift, and combined with its antique API, I anticipate it being replaced by something else soon.