I've been looking for a few days and I'm still can't find a solution.
I'd like to group a list of structs that are binding in a list, and still be able to update them.
In the example below I'd like to be able to toggle isOn and the bindable array be updated. This is as close as I've got...
enum UserType: Int, CaseIterable {
case one = 1
case two = 2
}
struct User: Identifiable {
var id = UUID()
var name: String
var type: UserType
var isOn: Bool
}
struct UserView: View {
@State var users: [User] = [
User(name: "James", type: .one, isOn: false),
User(name: "Josh", type: .two, isOn: false),
User(name: "Jim", type: .one, isOn: false),
User(name: "Jake", type: .two, isOn: false)
]
var body: some View {
List(){
ForEach(UserType.allCases) { type in
Section(header: Text("\(type.rawValue)")) {
ForEach(users) { user in
Text("user.name")
Toggle(isOn: user, label: Text("isOn"))
}
}
}
}
}
}
You should change your Data models to a
classinstead of astruct.It is how Apple recommends managing model data
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
It requires changing the model a little
And using
@ObservedObjectto see changes and use@Bindingfor the value types.Then your
UserViewcan look something like.For iOS 17
@PublishedandObservableObjectare no longer used you use use@Observablebut you can adapt your code with a few changes.And use
@Bindablefor the row.