Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active May 12, 2024 09:27
Show Gist options
  • Save JadenGeller/4344fc84e8073f7a63985a2c2a4a7e4e to your computer and use it in GitHub Desktop.
Save JadenGeller/4344fc84e8073f7a63985a2c2a4a7e4e to your computer and use it in GitHub Desktop.
useful property wrapper for prefix sums
@propertyWrapper
struct Versioned<Value>: RandomAccessCollection {
private var history: [Value]
var startIndex: Int { 0 }
var endIndex: Int { allValues.endIndex }
subscript(position: Int) -> Value {
get { allValues[position] }
set { allValues[position] = newValue }
}
init(wrappedValue: Value) {
self.history = [wrappedValue]
}
var wrappedValue: Value {
get { allValues[allValues.endIndex - 1] }
set { allValues[allValues.endIndex - 1] = newValue }
}
var projectedValue: Versioned<Value> {
get { self }
set { self = newValue }
}
mutating func commit() {
allValues.append(wrappedValue)
}
mutating func commit(_ newValue: Value) {
allValues.append(newValue)
}
mutating func commit(_ updateValue: (inout Value) -> Void) {
allValues.append(updateValue(&wrappedValue))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment