代码之家  ›  专栏  ›  技术社区  ›  Szymon W

weakbox要求weakarray<element>。element是类类型

  •  1
  • Szymon W  · 技术社区  · 6 年前

    我正试图实现一个存储来自objc会谈的弱引用解决方案( https://www.objc.io/blog/2017/12/28/weak-arrays/ )但我不能让它工作。

    确切的错误信息显示:

    'WeakBox' requires that 'WeakArray<Element>.Element' (aka 'Optional<Element>') be a class type
    

    enter image description here

    用这个代码:

    final class WeakBox<A: AnyObject> {
        weak var unbox: A?
    
        init(_ value: A) {
            unbox = value
        }
    }
    
    struct WeakArray<Element: AnyObject> {
        private var items: [WeakBox<Element>] = []
    
        init(_ elements: [Element]) {
            items = elements.map { WeakBox($0) }
        }
    
        init() {}
    }
    
    extension WeakArray: Collection {
        var startIndex: Int { return items.startIndex }
        var endIndex: Int { return items.endIndex }
    
        subscript(_ index: Int) -> Element? {
            return items[index].unbox
        }
    
        func index(after idx: Int) -> Int {
            return items.index(after: idx)
        }
    
        mutating func append(_ element: Element) {
            items.append(WeakBox(element))
        }
    
        mutating func removeAll() {
            items.removeAll()
        }
    }
    

    **

    更新:

    **

    过了一段时间,我意识到错误信息完全是误导性的。真正的问题是调用 序列 协议。例如,在下面添加类似的内容会从上面的屏幕截图中生成一条错误消息。但我还没有找到解决办法。

        class De {
            let de = "de"
        }
    
        let de = De()
        var ar = WeakArray<De>([])
        ar.append(de)
        ar.append(de)
    
        ar.forEach({ $0 })
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Isaac Paul    6 年前

    我相信“元素”正被SDK在某处重新定义。将元素重命名为t可以解决此问题。

    import Foundation
    
    final class WeakBox<T:AnyObject> {
        weak var unbox: T?
        init(_ value: T?) {
            unbox = value
        }
    }
    
    struct WeakArray<T: AnyObject> {
        private var items: [WeakBox<T>] = []
    
        init(_ elements: [T]) {
            items = elements.map { WeakBox($0) }
        }
    
        init(_ elements: [T?]) {
            items = elements.map { WeakBox($0) }
        }
    
        mutating func append(_ obj:T?) {
            items.append(WeakBox(obj))
        }
    
        mutating func remove(at:Int) {
            items.remove(at: at)
        }
    }
    
    extension WeakArray: Collection {
        var startIndex: Int { return items.startIndex }
        var endIndex: Int { return items.endIndex }
    
        subscript(_ index: Int) -> T? {
            return items[index].unbox
        }
    
        func index(after idx: Int) -> Int {
            return items.index(after: idx)
        }
    }