Faciliate access to properties of a binding

This commit is contained in:
david-swift 2024-01-04 14:49:45 +01:00
parent 8911cc8f42
commit eea842891e
2 changed files with 19 additions and 0 deletions

View File

@ -38,6 +38,7 @@
/// }
/// ```
@propertyWrapper
@dynamicMemberLookup
public struct Binding<Value> {
/// The value.
@ -64,6 +65,17 @@ public struct Binding<Value> {
/// The closure for settings the value.
private let setValue: (Value) -> Void
/// Get a property of any content of a `Binding` as a `Binding`.
/// - Parameter dynamicMember: The path to the member.
/// - Returns: The binding.
public subscript<Subject>(dynamicMember keyPath: WritableKeyPath<Value, Subject>) -> Binding<Subject> {
.init {
wrappedValue[keyPath: keyPath]
} set: { newValue in
wrappedValue[keyPath: keyPath] = newValue
}
}
/// Initialize a property that is bound from a parent view.
/// - Parameters:
/// - get: The closure for getting the value.

View File

@ -131,6 +131,13 @@ struct ChangeTextView: View {
}
```
If you have a more complex type and want to pass a property of the type as a binding,
you can just access the property on the binding.
```swift
HelloView(text: $complexType.text)
```
Whenever you modify a state property (directly or indirectly through bindings),
the user interface gets automatically updated to reflect that change.