[英]Convert class to generic with 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>??????? 如何将其转换为通用,MyDelegate可以成为<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. 没有必要制作这个Generic。 It is even a bad approach.
这甚至是一个糟糕的方法。 Just create multiple protocols that all conform to
MyDelegate
. 只需创建多个符合
MyDelegate
协议即可。
Make sure that DelegateMulticast
only uses the methods defined in MyDelegate
, and not any from subsequent protocols. 确保
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
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.