Reputation: 73
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.
Upvotes: 2
Views: 4005
Reputation: 257533
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: "")]
Upvotes: 3