How to do bindings to elements in a collection?

I have the following scenario that I want to implement

Code Block swift
import SwiftUI
struct Deck: Identifiable {
    var id: String { name }
    var name: String
}
struct DemoListView: View {
    @State var decks: [Deck] = [
        Deck(name: "Dark Magician"),
        Deck(name: "Eldlich"),
        Deck(name: "Hero"),
        Deck(name: "Hero Isolde"),
        Deck(name: "Orcust"),
        Deck(name: "Dino"),
        Deck(name: "Salamangreat"),
        Deck(name: "Sky Striker"),
    ]
    var body: some View {
        NavigationView {
            List {
                ForEach(0..<decks.count) { index in
                    DemoItemView(text: decks[index].name)
                }
            }
            .listStyle(SidebarListStyle())
            .frame(minWidth: 200, alignment: .leading)
        }
    }
}
struct DemoItemView: View {
    @Binding var text: String
    @State var isEditing: Bool = false
    var body: some View {
        Group {
            if isEditing {
                TextField(text, text: $text, onCommit: { isEditing.toggle() })
                    .textFieldStyle(PlainTextFieldStyle())
            } else {
                HStack {
                    Text(text)
                        .font(.headline)
                    Spacer()
                }
            }
        }
    }
}


In summary:
  • I have a list of Deck models

  • I want to display them on a List

  • If an element of the list is double tapped then I will toggle the element's isEditing property

  • when the text is editing, I will use a TextField that needs a binding to the edited text

  • the text comes from a property of Deck, which is an element in the array

The line of code

Code Block swift
DemoItemView(text: decks[index].name)


Is not correct, but this is why I am trying to achieve. I'm trying to get a binding to an element of the collection if that's even possible.

Maybe I took the wrong approach to solve this problem, if so I would like some advice.

At the end I want to implement a list of element and be able to edit inline the text of those elements (in macOS).
Answered by OOPer in 619124022
Please try this:
Code Block
                    DemoItemView(text: self.$decks[index].name)

When you have a Binding to an Array, adding subscript generates a binding to the element of the Array.

(This feature did not work for Dictionary in Xcode 11, not tested yet in Xcode 12.)
Accepted Answer
Please try this:
Code Block
                    DemoItemView(text: self.$decks[index].name)

When you have a Binding to an Array, adding subscript generates a binding to the element of the Array.

(This feature did not work for Dictionary in Xcode 11, not tested yet in Xcode 12.)
How to do bindings to elements in a collection?
 
 
Q