Skip to content

Instantly share code, notes, and snippets.

@klundberg
Created June 28, 2023 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klundberg/a68b47f7c16f0d4770ad62034397c513 to your computer and use it in GitHub Desktop.
Save klundberg/a68b47f7c16f0d4770ad62034397c513 to your computer and use it in GitHub Desktop.
A mutable variant of Binding.constant to help with swiftui previews
extension Binding {
/// like Binding.constant but lets you update the value and stores that updated value via a captured enclosing reference.
public static func initially(_ value: Value) -> Binding<Value> {
let box = Box(value)
return .init(
get: { box.value },
set: { box.value = $0 }
)
}
private class Box<Value> {
var value: Value
init(_ value: Value) { self.value = value }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment