WeakArray improvements

This commit is contained in:
Shadowfacts 2020-09-20 11:27:14 -04:00
parent 0d972d987c
commit b80a61cc95
Signed by untrusted user: shadowfacts
GPG Key ID: 94A5AB95422746E5

View File

@ -16,12 +16,16 @@ fileprivate class WeakWrapper<T: AnyObject> {
}
}
struct WeakArray<Element: AnyObject>: Collection {
struct WeakArray<Element: AnyObject>: MutableCollection, RangeReplaceableCollection {
private var array: [WeakWrapper<Element>]
var startIndex: Int { array.startIndex }
var endIndex: Int { array.endIndex }
init() {
array = []
}
init(_ elements: [Element]) {
array = elements.map { WeakWrapper($0) }
}
@ -30,11 +34,20 @@ struct WeakArray<Element: AnyObject>: Collection {
array = elements.map { WeakWrapper($0) }
}
subscript(_ index: Int) -> Element? {
return array[index].value
subscript(position: Int) -> Element? {
get {
array[position].value
}
set(newValue) {
array[position] = WeakWrapper(newValue)
}
}
func index(after i: Int) -> Int {
return array.index(after: i)
}
mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C : Collection, Self.Element == C.Element {
array.replaceSubrange(subrange, with: newElements.map { WeakWrapper($0) })
}
}