Created
September 6, 2024 20:49
-
-
Save JadenGeller/7e7faf57f88679b581c917d7f014fed1 to your computer and use it in GitHub Desktop.
push/pop state property wrapper
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 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 { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fyi
Underflow
error is not nested bc of compiler bug