41 lines
841 B
Swift
41 lines
841 B
Swift
|
//
|
||
|
// WeakArray.swift
|
||
|
// Tusker
|
||
|
//
|
||
|
// Created by Shadowfacts on 3/25/20.
|
||
|
// Copyright © 2020 Shadowfacts. All rights reserved.
|
||
|
//
|
||
|
|
||
|
import Foundation
|
||
|
|
||
|
fileprivate class WeakWrapper<T: AnyObject> {
|
||
|
weak var value: T?
|
||
|
|
||
|
init(_ value: T?) {
|
||
|
self.value = value
|
||
|
}
|
||
|
}
|
||
|
|
||
|
struct WeakArray<Element: AnyObject>: Collection {
|
||
|
private var array: [WeakWrapper<Element>]
|
||
|
|
||
|
var startIndex: Int { array.startIndex }
|
||
|
var endIndex: Int { array.endIndex }
|
||
|
|
||
|
init(_ elements: [Element]) {
|
||
|
array = elements.map { WeakWrapper($0) }
|
||
|
}
|
||
|
|
||
|
init(_ elements: [Element?]) {
|
||
|
array = elements.map { WeakWrapper($0) }
|
||
|
}
|
||
|
|
||
|
subscript(_ index: Int) -> Element? {
|
||
|
return array[index].value
|
||
|
}
|
||
|
|
||
|
func index(after i: Int) -> Int {
|
||
|
return array.index(after: i)
|
||
|
}
|
||
|
}
|