2

I'm struggling to do a simple append in SwiftUI. Here's my code:

// This is defined in my custom view
var newClass = Class()

// This is inside a List container (I hid the Button's content because it doesn't matter)
Button(action: {
    self.newClass.students.append(Student())
    print(self.newClass.students) // This prints an Array with only one Student() instance - the one defined in the struct's init
})

// These are the custom structs used
struct Class: Identifiable {
    var id = UUID()
    @State var name = ""
    @State var students: [Student] = [Student()] // Right here
}

struct Student: Identifiable {
    var id = UUID()
    @State var name: String = ""
}

I think it might be somehow related to the new @Struct thing, but I'm new to iOS (and Swift) development, so I'm not sure.

2
  • what if you remove @State from the properties in Class? Commented Mar 7, 2020 at 18:57
  • 1
    Trying that! The compiler throws an error ("Cannot use mutating member on immutable value: 'self' is immutable"), but I think it can be fixed. Commented Mar 7, 2020 at 19:02

1 Answer 1

3

Let's modify model a bit...

struct Class: Identifiable {
    var id = UUID()
    var name = ""
    var students: [Student] = [Student()]
}

struct Student: Identifiable {
    var id = UUID()
    var name: String = ""
}

... and instead of using @State in not intended place (because it is designed to be inside View, instead of model), let's introduce View Model layer as

class ClassViewModel: ObservableObject {
    @Published var newClass = Class()
}

and now we can declare related view that behaves as expected

struct ClassView: View {
    @ObservedObject var vm = ClassViewModel()

    var body: some View {
        Button("Add Student") {
            self.vm.newClass.students.append(Student())
            print(self.vm.newClass.students)
        }
    }
}

Output:

Test[4298:344875] [Agent] Received display message [Test.Student(id: D1410829-F039-4D15-8440-69DEF0D55A26, name: ""), Test.Student(id: 50D45CC7-8144-49CC-88BE-598C890F2D4D, name: "")]

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Turns out I managed to make it work just by removing @State from Class (but not from Student, since that would make the compiler throw an error). It's working finecase anything else goes wrong (and this is very likely to happen), I will certainly try your suggestion!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.