Skip to content

Best Practices for Bindings with Nested State in TCA? #3691

Answered by mbrandonw
atimca asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @atimca, this is a problem that goes beyond TCA. You would have the exact same problem in vanilla SwiftUI. The moment you cross the boundary of an optional you lose writability in key paths. The only thing you can do is define custom properties on your types to bridge to the non-optional world in order to maintain writability.

These new properties can either be ad hoc or can be generic. For example, if you had a subscript like so:

extension Optional {
  subscript(coalesce value: Wrapped) -> Wrapped {
    get { self ?? value }
    set { self = newValue }
  }
}

…then you would be able to do:

$store
  .response[coalesce: Response()]
  .items[coalesce: []][id: id][coalesce: Item()]
  .isOn

S…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@atimca
Comment options

Answer selected by atimca
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants