I have this class for multicast delegate:
//Multicast delegate per i Ping
class DelegateMulticast {
private var notifiers: [MyDelegate] = []
func pingReceived() {
notifyAll { notifier in
notifier.pingReceived()
}
}
func addNotifier(notifier: MyDelegate) {
notifiers.append(notifier)
}
func removeNotifier(notifier: MyDelegate) {
for (var i=0; i<notifiers.count; ++i) {
if notifiers[i] === notifier {
notifiers.removeAtIndex(i)
break;
}
}
}
private func notifyAll(notify: MyDelegate -> ()) {
for notifier in notifiers {
notify(notifier)
}
}
}
How can I convert this to generic, MyDelegate can become <T>??????? my goal is to use:
let a: DelegateMulticast = DelegateMulticast (MyDelegate)
let a: DelegateMulticast = DelegateMulticast (MyDelegate2)
etc...
There is no need to make this Generic. It is even a bad approach. Just create multiple protocols that all conform to MyDelegate.
Make sure that DelegateMulticast only uses the methods defined in MyDelegate, and not any from subsequent protocols.
protocol MyDelegate {
func pingReceived()
}
protocol MyDelegate2 : MyDelegate {
}
class DelegateMulticast {
private var notifiers: [MyDelegate] = []
func addNotifier(notifier: MyDelegate) {
notifiers.append(notifier)
}
}
class Alpha : MyDelegate {
func pingReceived() {
//
}
}
class Beta : MyDelegate2 {
func pingReceived() {
//
}
}
let test = DelegateMulticast()
test.addNotifier(Alpha()) // works
test.addNotifier(Beta()) // works
Generic approach :
class DelegateMulticast<T : MyDelegate> {
private var notifiers: [T] = []
func addNotifier(notifier: T) {
notifiers.append(notifier)
}
}
class Alpha : MyDelegate {
func pingReceived() {
//
}
}
class Beta : Alpha, MyDelegate2 { // notice the subclassing and the conformance
}
let test = DelegateMulticast<Alpha>()
test.addNotifier(Alpha())
test.addNotifier(Beta())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With