Having problems with appending to an array in SwiftUI.
I'm on Xcode 11 beta 7 and using the updated ObservableObject
, EnvironmentObject
and Published
syntax on a watchOS app. WKHostingControlle
r expects concrete types so passing ContentView().environmentObject(subject) is not possible
.
This line crashes the app:
self.subjectData.store.append(Subject(name: self.addedSubject, isFavorite: false))
Any ideas on what is wrong?
struct Subject: Codable, Identifiable {
var id: UUID = UUID()
var name: String
var isFavorite: Bool
}
class SubjectDataEnv: ObservableObject {
@Published var store = [
Subject(name: "Physics", isFavorite: true),
Subject(name: "Science", isFavorite: false)
]
@Published var selectedSubject = Subject(name: "Subject 1", isFavorite: false)
}
class HostingController: WKHostingController<ContentView> {
override var body: ContentView {
return ContentView()
}
}
struct ContentView: View {
@State var subjectData = SubjectDataEnv()
var body: some View {
SubjectView().environmentObject(subjectData)
}
}
struct SubjectView: View {
@EnvironmentObject var subjectData: SubjectDataEnv
var body: some View {
List {
ForEach(subjectData.store) { subject in
NavigationLink(destination: DurationView()
.environmentObject(self.subjectData)
)
}
NavigationLink(destination: AddSubjectView()
.environmentObject(self.subjectData)
) {
Text("+")
}
}
}
}
struct AddSubjectView: View {
@EnvironmentObject var subjectData: SubjectDataEnv
@State var addedSubject: String = "subject"
var body: some View {
VStack(alignment: .leading, spacing: 0) {
TextField("Add your subject", text: $addedSubject)
Button(action: {
self.subjectData.store.append(Subject(name: self.addedSubject, isFavorite: false)) // crashes the app
}) {
Text("Done")
}
}
}
}