Skip to content

Instantly share code, notes, and snippets.

@chrishulbert
Created March 3, 2015 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

The first @objc is required so that anything that adheres to 'MyManagerDelegate' is able to be added to the NSHashTable. The second @objc is required so that the protocol can pass a MyManager as its function's first argument.

@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