我想像这样创建一个弱引用委托(delegate)数组...
fileprivate class WeakDelegate<T:AnyObject> {
weak var value:T?
init (value:T) {
self.value = value
}
}
class Radio {
private var delegates = [WeakDelegate<AnyObject>]()
}
到目前为止这么好......?我还想做的是以这两种方式整理我的数组...
1.
func removeDeadDelegates() {
let liveDelegates = delegates.filter { $0.value != nil }
delegates = liveDelegates
}
和 2.
func remove<T>(specificDelegate:T) {
let filteredDelegates = delegates.filter { $0.value != specificDelegate }
listeners = filteredDelegates
}
说 无法将类型“T”的值转换为预期的参数类型“_OptionalNilComparisonType”
现在我可以添加这个来让警告像这样消失......
let liveDelegates = delegates.filter {
if let d = specificDelegate as? _OptionalNilComparisonType {
return $0.value != d
}
return true
}
但是这个转换不起作用...
我很担心,因为我不确定这意味着什么……谁能解释为什么我不能将泛型与 ==
进行比较,以及为什么这个转换失败了?
谢谢你的时间
编辑
像这样?
func remove<T:AnyObject>(delegate:T) {
let filteredDelegates = delegates.filter { $0.value != delegate }
delegates = filteredDelegates
}
遗憾的是没有快乐......
最佳答案
类类型的实例可以与“等同于”进行比较
===
和“不完全相同”!==
运算符:
func remove(specificDelegate: AnyObject) {
let filteredDelegates = delegates.filter { $0.value !== specificDelegate }
delegates = filteredDelegates
}
同样适用于泛型方法
func remove<T:AnyObject>(specificDelegate: T) {
let filteredDelegates = delegates.filter { $0.value !== specificDelegate }
delegates = filteredDelegates
}
(但我还没有看到这样做的好处)。
关于swift - Swift 中的 Compare/Equatable 弱泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49544195/