Last active
September 6, 2024 20:49
-
-
Save JadenGeller/4344fc84e8073f7a63985a2c2a4a7e4e to your computer and use it in GitHub Desktop.
useful property wrapper for prefix sums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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
similar: https://gist.github.com/JadenGeller/7e7faf57f88679b581c917d7f014fed1