代码之家  ›  专栏  ›  技术社区  ›  Magoo

Swift中的比较/等价弱泛型

  •  1
  • Magoo  · 技术社区  · 7 年前

    我想创建一个弱引用代理数组,如。。。

    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
    }
    

    表示 Cannot convert value of type 'T' to expected argument type '_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
    }
    

    没有快乐可悲。。。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Martin R    7 年前

    类类型的实例可以与 === 和–不完全相同 !== 操作员:

    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
    }
    

    (但我还没有看到这样做的好处)。

    推荐文章