// // Weak.swift // Tusker // // Created by Shadowfacts on 3/25/20. // Copyright © 2020 Shadowfacts. All rights reserved. // import Foundation final class WeakHolder { weak var object: T? init(_ object: T?) { self.object = object } } struct WeakArray: MutableCollection, RangeReplaceableCollection, RandomAccessCollection, BidirectionalCollection { private var array: [WeakHolder] var startIndex: Int { array.startIndex } var endIndex: Int { array.endIndex } init() { array = [] } init(_ elements: [Element]) { array = elements.map { WeakHolder($0) } } init(_ elements: [Element?]) { array = elements.map { WeakHolder($0) } } subscript(position: Int) -> Element? { get { array[position].object } set(newValue) { array[position] = WeakHolder(newValue) } } func index(after i: Int) -> Int { return array.index(after: i) } func index(before i: Int) -> Int { return array.index(before: i) } mutating func replaceSubrange(_ subrange: Range, with newElements: C) where C : Collection, Self.Element == C.Element { array.replaceSubrange(subrange, with: newElements.map { WeakHolder($0) }) } }