Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert class to generic with Swift

Tags:

generics

swift

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...

like image 252
Luca Becchetti Avatar asked Jan 26 '26 00:01

Luca Becchetti


1 Answers

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())
like image 141
R Menke Avatar answered Jan 29 '26 18:01

R Menke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!