作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有这个类用于多播委托(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/
我是一名优秀的程序员,十分优秀!