【发布时间】:2020-06-20 04:41:29
【问题描述】:
我正在努力在 SwiftUI 中做一个简单的追加。这是我的代码:
// 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 = ""
}
我认为这可能与新的 @Struct 事物有关,但我是 iOS(和 Swift)开发的新手,所以我不确定。
【问题讨论】:
-
如果从
Class的属性中删除@State 会怎样? -
试试吧!编译器会抛出一个错误(“Cannot use mutating member on immutable value: 'self' is immutable”),但我认为可以修复。
标签: ios arrays swift append swiftui