Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created September 6, 2024 20:49
Show Gist options
  • Save JadenGeller/7e7faf57f88679b581c917d7f014fed1 to your computer and use it in GitHub Desktop.
Save JadenGeller/7e7faf57f88679b581c917d7f014fed1 to your computer and use it in GitHub Desktop.
push/pop state property wrapper
@propertyWrapper
struct Stack<Value> {
private var history: [Value]
init(wrappedValue initialValue: Value) {
self.history = [initialValue]
}
var wrappedValue: Value {
get { history[history.endIndex - 1] }
_modify { yield &history[history.endIndex - 1] }
set { history[history.endIndex - 1] = newValue }
}
var projectedValue: Self {
return self
}
mutating func push() {
history.append(wrappedValue)
}
mutating func pop() throws {
guard history.count > 1 else { throw UnderflowError() }
history.removeLast()
}
}
struct UnderflowError: Error { }
@JadenGeller
Copy link
Author

fyi Underflow error is not nested bc of compiler bug

@JadenGeller
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment