I am struggling with exactly how to set up SwiftData relationships, beyond the single relationship model...
Let's say I have a school. Each school offers a set of classes. Each class is taught by one teacher and attended by several students. Teachers may teach more than one class, but only at one school. Similarly students may attend more than one class, but only at one school. Classes themselves may be offered at more than one school.
Can someone create a class for School, SchoolClass, Teacher, and Student with id, name, and relationships... I have tried it unsuccessfully about 10 different ways at this point.
My most recent is below... I am struggling getting beyond a school listing in the app, and I'll cross that bridge next. I am just wondering if all the trouble I am having is because I am not smart with the class definitions. And wondering if this is to complex for SwiftData and CoreData is the requirement. This is not a real app, just my way of really trying to get a handle on Swift Data models and Navigation.
I am very new to Swift, and will take any and all suggestions with enthusiasm! Thanks for taking the time.
import Foundation
import SwiftData
@Model
class School: Identifiable {
var id: UUID = UUID()
var name: String
var mascot: String
var teachers: [Teacher]
var schoolClasses: [SchoolClass]
init (name: String, mascot: String = "", teachers: [Teacher] = [], schoolClasses: [SchoolClass] = []) {
self.name = name
self.mascot = mascot
self.teachers = teachers
}
class SchoolClass: Identifiable {
var id: UUID = UUID()
var name: String
var teacher: Teacher?
var students: [Student] = []
init (name: String, teacher: Teacher? = nil, students: [Student] = []) {
self.name = name
self.teacher = teacher
self.students = students
}
}
class Teacher: Identifiable {
var id: UUID = UUID()
var name: String
var tenured: Bool
var school: School?
var students: [Student] = []
init (name: String, tenured: Bool = false, students: [Student] = []) {
self.name = name
self.tenured = tenured
self.students = students
}
}
class Student: Identifiable {
var id: UUID = UUID()
var name: String
var grade: Int?
var teacher: Teacher?
init (name: String, grade: Int? = nil, teacher: Teacher? = nil) {
self.name = name
self.grade = grade
self.teacher = teacher
}
}
}