Tusker/Tusker/Weak.swift

58 lines
1.3 KiB
Swift
Raw Normal View History

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