J. Raji
J. Raji

Reputation: 143

How to modify List Data in SwiftUI

I want to change the value of a object associated to an item in a List when the user tap in that item and I get the next error "Cannot assign to property: 'student' is a 'let' constant". How do I prevente this to happened?

Here is my code:

import SwiftUI

var students: [Student] = load("studentsData.json")

struct StudentsListView: View {
    @EnvironmentObject var viewRouter:ViewRouter

    var body: some View {
        NavigationView{
            List(students){student in
                Button(action: {
                    student.isInClass = true
                }){
                    StudentItemListView(student: student)
                }
            }
        }
    }
}

struct StudentsListView_Previews: PreviewProvider {
    static var previews: some View {
        StudentsListView().environmentObject(ViewRouter())
    }
}

struct StudentItemListView: View {
    var student:Student

    var body: some View {
        HStack {
            Image("profile")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width:50, height:50)
                .clipShape(Circle())
            VStack(alignment: .leading){
                Text(student.firstName + " " + student.lastName)
                    .font(.headline)
                if(student.isInClass == true){
                    Text("Asistió")
                    .font(.subheadline)
                    .foregroundColor(.green)
                } else {
                    Text("Faltó")
                    .font(.subheadline)
                    .foregroundColor(.red)
                }
            }
            Spacer()
        }.padding()
    }
}

Upvotes: 1

Views: 1483

Answers (1)

Luis
Luis

Reputation: 1009

As @koen mentioned in the comment, you should be using @State or @EnvironmentObject for accessing/mutating variables and state in your SwiftUI views.

Unlike UIKit, you might notice how SwiftUI relies on the heavy usage of structs. Structs are immutable by default, this means that you cannot modify any part of a struct without clearly telling the compiler that the struct is mutable (using var keyword, etc.) The way to manage state in SwiftUI is with the use of the Combine framework and the use of @State properties, etc. From a brief look at your code, it looks like all you need to do is add @State var student: Student to your StudentItemListView.

If this at all sounds confusing or you are unaware of what @State might be, I highly recommend either watching the 2019 WWDC videos and look at the Apple provided SwiftUI tutorial.

Upvotes: 1

Related Questions