arraysswiftswiftuiswiftdataswiftui-environment

SwiftData not refreshing with Array


I have a SwiftUI + SwiftData project where I'm displaying a list of pet allergies in my HealthInformationView.
From this View, I can open another one to add new allergies, as well as delete some.

Here's my Model :

@Model
final class Pet {
    var name: String
    var health: Health?

    // Rest of code
}

@Model
final class Health {
    var allergies: [String]?

    // Rest of code
}

And here's my Views :

struct HealthInformationView: View {
    @Environment(Pet.self) var pet: Pet
    @State private var showEditHealthInformations = false

    var body: some View {
        VStack {
            Button("Edit Health Informations") {
                showEditHealthInformations = true
            }

            if let allergies = pet.health?.allergies {
                Text(allergies.joined(separator: ", "))
                    .padding()
            } else {
                Text("No allergies listed.")
            }
        }
        .sheet(isPresented: $showEditHealthInformations) {
            EditHealthInformationView()
        }
    }
}

struct EditHealthInformationView: View {
    @Environment(Pet.self) var pet: Pet
    @Environment(\.dismiss) var dismiss
    @State private var allergies: [String] = []

    var body: some View {
        NavigationStack {
            VStack {
                ForEach(allergies.indices, id: \.self) { index in
                    // Minus Button + Allergy TextField
                    HStack {
                        Button {
                            if allergies.indices.contains(index) {
                                allergies.remove(at: index)
                            }
                        } label: {
                            Image(systemName: "minus.circle.fill")
                        }

                        if allergies.indices.contains(index) {
                            TextField("Allergie \(index + 1)", text: $allergies[index])
                                .textFieldStyle(RoundedBorderTextFieldStyle())
                                .padding(.vertical, 4)
                        }
                    }
                }

                // Create a new Allergy
                Button {
                    allergies.append("")
                } label: {
                    HStack {
                        Image(systemName: "plus.circle.fill")
                        Text("Ajouter une allergie")
                    }
                    .font(.title3)
                }
            }
            .onAppear {
                allergies = pet.health?.allergies ?? []
            }
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button("Save") {
                        if pet.health == nil {
                            pet.health = Health()
                        }

                        pet.health?.allergies = allergies
                        dismiss()
                    }
                }
            }
        }
    }
}

When the Pet doesn't have a Health object yet, everything works fine: I add allergies, save them, and when the modal view dismisses, changes are reflected correctly in HealthInformationView.

But here's my problem, when the pet already have a Health object, the modifications doesn't reflect on HealthInformationView.
I'm forced to hit the return button and to re-open it to see the changes.

Do you have any ideas what I'm doing wrong ?

I tried not to use a Modal view, but it's the same.

Edit

Ok, I might have found the reason of my problem. Pet is a class, so a reference type. But Health too !

So I'm trying to update an Array of String (allergies) which is inside Health (reference type), inside Pet (reference too). So it's apparently normal that the UI isn't refreshed, because it doesn't detect the change since it's a reference type !

I would have use objectWillChange.send(), but with @Observable, is doesn't exist anymore... So if you have a solution, I'll be released from this ! Thank you :)


Solution

  • I've found an answer.

    I have just revisited my Data structure and made Allergy a struct, so now it is a Value Type and the View refreshes.

    I don't know if it's the best solution, but it works.