Convert class to generic with Swift

时间:2015-12-14 18:01:16

标签: swift generics

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

1 个答案:

答案 0 :(得分:3)

没有必要制作这个Generic。这甚至是一个糟糕的方法。只需创建多个符合MyDelegate的协议。

确保DelegateMulticast仅使用MyDelegate中定义的方法,而不是后续协议中的任何方法。

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

通用方法:

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())