我正试图实现一个存储来自objc会谈的弱引用解决方案(
https://www.objc.io/blog/2017/12/28/weak-arrays/
)但我不能让它工作。
确切的错误信息显示:
'WeakBox' requires that 'WeakArray<Element>.Element' (aka 'Optional<Element>') be a class type
用这个代码:
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 })