5

I have a struct User with a list of hobbies as follows:

struct User: Hashable, Codable, Identifiable, Equatable {
    var id: String
    var name: String
    var hobbies: [String]
}

I then generate a list view using a list of users as a state variable. When the button in the list view is clicked a new hobby is added to a user's hobbies.

struct UsersListView: View {

    @State var users: [User]


    var body: some View {

                TitleView(titleText: "Friends")
                    .padding(.leading, 30.0)

                List(userDisplayList) { user in
                     Text(user.name)
                     Text(user.hobbies.joined(separator: ", "))
                     Button(action: {self.users[0].hobbies.append("new hobby")}
                }
            }
        }
    }
}

However, when I click on the button, the users state variable does not change and remains the same. Can anyone explain what is going on here?

chinloong
  • 79
  • 1
  • 7
  • 1
    why you don't just wrap your User in Observableobject? – Ernist Isabekov Feb 07 '20 at 07:57
  • Wouldn't wrapping it in ObservableObject necessitate converting it from a struct to a class, which may carry other issues along with it...? I think there are some complexity with classes not having default values and no initializer that he may be trying to avoid, perhaps. – ChrisH Mar 08 '21 at 15:21

2 Answers2

1

You display every user in userDisplayList, not in users.

So when you change some value in users, SwiftUI think that there is nothing to update in your view, since nothing depends on users variable.

Try using List(users) { user in instead if there is no additional logic in your userDisplayList.

Lieksu
  • 71
  • 4
0

Try this:

    struct User: Hashable, Codable, Identifiable, Equatable {
    var id = UUID()
    var name: String
    var hobbies: [String]
}

struct UsersListView: View {

    @State var users: [User] = [User(name: "aaaa", hobbies: [])]


    var body: some View {

        List(users) { user in
                     Text(user.name)
                     Text(user.hobbies.joined(separator: ", "))
                        Button(action: {
                            self.users[0].hobbies.append("new hobby")
                        }) {
                            Text("Create hobby")
                        }

                }
            }
        }
Andoni Da Silva
  • 1,161
  • 15
  • 31