SwiftUI: Cannot find '$lektion' in scope

I want to use a Toggle() but when I give it an isOn Variable it says:

Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'

When I then try to sign the variable with a $ it says:

Cannot find '$lektion' in scope

Here is my Code:

import SwiftUI
import SwiftData


struct LektionenView: View {
    @Environment(\.modelContext) private var modelContext
    @Query(sort: \Lektion.id) private var lektionen: [Lektion]
    
    @State var isPresented: Bool = false

    var body: some View {
        List {
            ForEach(lektionen) { lektion in
                NavigationLink {
                    VokabelnView(lektion: lektion).navigationTitle("Vokabeln")
                } label: {
                    Toggle("", isOn: $lektion.isOn)
                }
            }
            .onDelete(perform: deleteItems)
        }.sheet(isPresented: $isPresented, content: {
            AddLektionView()
        }).toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                EditButton()
            }
            ToolbarItem {
                Button {
                    isPresented = true
                } label: {
                    Label("Add Item", systemImage: "plus")
                }
            }
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            for index in offsets {
                modelContext.delete(lektionen[index])
            }
        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: Lektion.self, inMemory: true)
}

You should try to change to:

    var body: some View {
        List {
            ForEach($lektionen) { $lektion in
                NavigationLink {
                    VokabelnView(lektion: $lektion).navigationTitle("Vokabeln")
                } label: {
                    Toggle("", isOn: $lektion.isOn)
                }
            }

The toggle requires a Binding to a boolean value but your lektion variable cannot provide one. The solution is to use the Bindable property wrapper like this:

ForEach(lektionen) { lektion in
    @Bindable var lektion = lektion // add this line

    NavigationLink {
        VokabelnView(lektion: lektion).navigationTitle("Vokabeln")
    } label: {
        Toggle("", isOn: $lektion.isOn)
    }
}

Now you can access $lektion which can create bindings to its properties.

SwiftUI: Cannot find '$lektion' in scope
 
 
Q