Reputation: 11
I want to display a separate SubjectView
in the MainView
.
The property topics
on subject
in SubjectView
is not accessible.
What should I do about it? Thanks.
Update:
ForEach(subject.topics, id: \.self) { topic in
Text(topic.title)
}
... could be the problematic part.
File: SubjectView
import SwiftUI
struct SubjectView: View {
@State var subject: Subject
var body: some View {
List {
ForEach(subject.topics, id: \.self) { topic in
Text(topic.title)
}
}
}
}
File MainView
import SwiftUI
struct MainView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Subject.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Subject.name, ascending: true)]) var subjects: FetchedResults<Subject>
@State var subjectName: String = ""
var body: some View {
NavigationView {
Form {
List {
ForEach(subjects, id: \.self) { subject in
NavigationLink(
destination: SubjectView(subject: subject),
label: {
Text(subject.name ?? "-")
})
}
}
}
.navigationTitle("Schulfächer")
}
}
}
Screenshot of the Subject entity
The error at SubjectView
: var body: some View
reads:
Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project
Upvotes: 0
Views: 76
Reputation: 29309
@State var subject: Subject
in SubjectView
should be
@ObservedObject var subject: Subject
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
@StateObject
is for initializing ObservableObject
s
As for your topics
ForEach((subject.topics.allObjects as? [Topic]) ?? [], id: \.self) { topic in
Should work
Upvotes: 0
Reputation: 285072
The collection type of ForEach
must conform to RandomAccessCollection
. topics
does not because it's an (NS)Set
.
A simple solution is to sort
the Set
which becomes an Array
. Or create an array explicitly, the line assumes that topics
is a native Swift Set<Topic>
Array(subject.topics)
Note: Do not use \.self
carelessly. Determine one attribute which is unique and/or adopt Identifiable
. For example you could use the NSManagedObjectID
of the NSManagedObject
instance which is unique.
Upvotes: 1