Extra argument 'selection' in call error in ListView.

Why am i getting the following error: Extra argument 'selection' in call? It works without the 'selection: $selection' parameter.

XCode Version 11.7

struct AlarmListView: View {
    @ObservedObject var alarmModel : AlarmModel
    @State var selection: String? = nil
    
    var body: some View {
        VStack {
            List {
                ForEach(alarmModel.alarms, id: \.self, selection: $selection) { alarm in /*error here*/
                    Text("\(alarm)")
                }
            }
        }
    }
}
class AlarmModel: ObservableObject {
    @Published var alarms: [String] = []
    
    func addAlarm(_ alarmTime: String) {
        alarms.append(alarmTime)
    }
    
    func removeAlarm(at index: Int) {
        alarms.remove(at: index)
    }

}
Answered by Claude31 in 748800022

The syntax is not correct, selection is for List, not ForEach.

Use .onTapGesture instead:

struct AlarmListView: View {
    @ObservedObject var alarmModel : AlarmModel
    @State var selection: String? = nil
    
    var body: some View {
        VStack {
            List {
                ForEach(alarmModel.alarms, id: \.self) { alarm in /*Change here*/
                    Text("\(alarm)")
                        .onTapGesture {
                            selection = "\(alarm)" // or maybe simply selection = alarm
                        }
                }
            }
        }
    }
}
Accepted Answer

The syntax is not correct, selection is for List, not ForEach.

Use .onTapGesture instead:

struct AlarmListView: View {
    @ObservedObject var alarmModel : AlarmModel
    @State var selection: String? = nil
    
    var body: some View {
        VStack {
            List {
                ForEach(alarmModel.alarms, id: \.self) { alarm in /*Change here*/
                    Text("\(alarm)")
                        .onTapGesture {
                            selection = "\(alarm)" // or maybe simply selection = alarm
                        }
                }
            }
        }
    }
}

Thanks, thats works! Extra question: how can I bind the selection variable to an other view in the easiest way? I have a button in the other view with which I want to delete the selected element.

You should close the thread and start a new one.

Not sure I understand all your questions.

how can I bind the selection variable to an other view in the easiest way?

  • selection variable: isn't it the String ?
  • You could create an environment var in which you copy the selected item.

How to get the selected item's id?

Why do you need the id ?

Extra argument 'selection' in call error in ListView.
 
 
Q