Skip to content

Instantly share code, notes, and snippets.

@KrisRJack
Last active May 30, 2022 12:12
Show Gist options
  • Save KrisRJack/f786071cf6e091dff74813cdc2f902d8 to your computer and use it in GitHub Desktop.
Save KrisRJack/f786071cf6e091dff74813cdc2f902d8 to your computer and use it in GitHub Desktop.
ReferenceArray
/*
Custom array represented as a reference type.
Unlike NSArray and NSMutableArray, this class
allows for observing changes realtime.
Created by Kristopher Jackson on 5/22/22.
*/
import Foundation
/// Custom array represented as a reference type
/// Contains a closures that allows for observing changes
open class ReferenceArray<T> {
private var objects: [T] {
didSet {
didUpdate?(oldValue)
}
willSet {
willUpdate?(newValue)
}
}
public var count: Int { objects.count }
public var isEmpty: Bool { count == .zero }
/// Observe changes to array
public var didUpdate: ((_ oldArray: [T]) -> Void)?
public var willUpdate: ((_ newArray: [T]) -> Void)?
init(_ array: [T]) {
objects = array
}
public func add(_ object: T) {
objects.append(object)
}
public func set(to newArray: [T]) {
objects = newArray
}
public func insert(_ object: T, at index: Int) {
objects.insert(object, at: index)
}
public func remove(at index: Int) -> T {
return objects.remove(at: index)
}
public func object(at index: Int) -> T {
return objects[index]
}
public func enumerated() -> EnumeratedSequence<[T]> {
return objects.enumerated()
}
// Useful if the objects being stored are
// value types that have modifiable properties.
public func modify(at index: Int, _ closure: (_ object: inout T) -> Void) {
closure(&objects[index])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment