How to use `@FocusedBinding` with optionals?

There was another post asking how to use @FocusedBinding .

I'm trying to use @FocusedBinding in the following context.
  • I have a view that contains a @State array property of type [DeckViewModel]

  • Within the view, I display the list of those models

  • I can tap on one item to select it, storing that selection in a @State var currentDeck: DeckViewModel? property.

Then I define the properties needed to use @FocusedBinding

Code Block swift
struct FocusedDeckKey : FocusedValueKey {
    typealias Value = Binding<DeckViewModel?>
}
extension FocusedValues {
    var currentDeck: FocusedDeckKey.Value? {
        get { self[FocusedDeckKey.self] }
        set { self[FocusedDeckKey.self] = newValue }
    }
}


And set the value in the view

Code Block swift
.focusedValue(\.currentDeck, $appState.currentDeck)


Finally, in the struct I try to set the preferences I use it like:

Code Block swift
struct AppCommands: Commands {
    @FocusedBinding(\.currentDeck) private var currentDeck: DeckViewModel?
}


Then I get the following error:

❌ Type of expression is ambiguous without more context

Which makes sense, as the FocusedValues.currentDeck is of type Binding<DeckViewModel?>?

So the syntax of

Code Block
@FocusedBinding(\.currentDeck) private var currentDeck: DeckViewModel?

is not correct for these types. But I am not sure how to express this correctly.

The idea of the binding to an optional value seems ok to me, but it brings this complexity regarding the types and this API.

Then.
  • How can I make @FocusedBinding work with this optional?

  • or How should I solve this issue? considering I'm trying to represent the selection of an item of a list

Thanks
I have exactly the same problem. Have you found a way to express this?

Try

struct FocusedDeckKey : FocusedValueKey {    
     typealias Value = Binding<DeckViewModel?>
}

extension FocusedValues {    
     var currentDeck: Binding<DeckViewModel?>? {        
          get { self[FocusedDeckKey.self] }        
          set { self[FocusedDeckKey.self] = newValue }   
      }
}

and

struct AppCommands: Commands {    
     @FocusedBinding(\.currentDeck) private var currentDeck
}

Thanks for the suggestion! While this did resolve the "type of expression is ambiguous without more context" error, a new problem was introduced: when I tried to access the property, the inferred type was a double optional. Using your app as an example, the type of the currentDeck would be currentDeck??. Has anybody encountered this issue?

Has someone managed to make it work with menu bar items on macOS Monterey? It seems FocusedBinding and FocusedValue are broken even on macOS 12.1.

How to use `@FocusedBinding` with optionals?
 
 
Q