Skip to content

Instantly share code, notes, and snippets.

@chrishulbert
Created March 3, 2015 04:26
Show Gist options
  • Save chrishulbert/71828c1f9efbfd131e6d to your computer and use it in GitHub Desktop.
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)
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)
}
}
}
@chrishulbert
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment