gpt4 book ai didi

swift - 使用 Swift 将类转换为泛型

转载 作者:搜寻专家 更新时间:2023-10-31 22:33:55 24 4
gpt4 key购买 nike

我有这个类用于多播委托(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)
}
}

}

如何将其转换为泛型,MyDelegate 可以变为 ??????我的目标是使用:

let a: DelegateMulticast = DelegateMulticast (MyDelegate)
let a: DelegateMulticast = DelegateMulticast (MyDelegate2)

等...

最佳答案

没有必要使这个通用。这甚至是一种糟糕的做法。只需创建多个均符合 MyDelegate 的协议(protocol)即可。

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


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

关于swift - 使用 Swift 将类转换为泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34273639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com