Skip to content

Instantly share code, notes, and snippets.

@NSEGeorge
Created September 16, 2019 16:49
Show Gist options
  • Save NSEGeorge/1f6a603e1fde25e195f087b5712efe37 to your computer and use it in GitHub Desktop.
Save NSEGeorge/1f6a603e1fde25e195f087b5712efe37 to your computer and use it in GitHub Desktop.
class WeakList<T: AnyObject> {
private class WeakRef {
private(set) weak var value: T?
init(_ value: T) {
self.value = value
}
}
private var arr = [WeakRef]()
var count: Int {
arr = arr.filter { $0.value != nil }
return arr.count
}
var allObjects: [T] {
let values = arr.map { $0.value }
return values.compactMap { $0 }
}
var lastObject: T? {
for i in (0..<arr.count).reversed() {
if let object = arr[i].value {
return object
} else {
arr.remove(at: i)
}
}
return nil
}
func addObject(_ object: T) {
arr.append(WeakRef(object))
}
func removeObject(_ object: T) -> Int? {
for i in 0..<arr.count {
if let item = arr[i].value {
if item === object {
arr.remove(at: i)
return i
}
} else {
arr.remove(at: i)
}
}
return nil
}
func removeLast() {
for i in (0..<arr.count).reversed() {
if arr.remove(at: i).value != nil {
return
}
}
}
func removeAllObjects() {
arr.removeAll()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment