In Swift, the two go-to tools for building custom data models are struct and class. A struct is a value type, so copying it creates a brand-new piece of data. A class is a reference type, so copying it usually just means both references point to the same single object.
For app models and simple data containers, it's a good idea to reach for struct first. Use class when you need shared mutable state or inheritance.
swift
struct Course {
var title: String
var lessonCount: Int
}
class Student {
var name: String
var enrolledCourse: Course?
init(name: String) {
self.name = name
}
}
let swiftCourse = Course(title: "Swift Basics", lessonCount: 20)
let student = Student(name: "Nandar")
student.enrolledCourse = swiftCourse
print(student.name)
print(student.enrolledCourse?.title ?? "No course")Course is a simple data model, so it's written as a struct. Student has an initializer and is written as a class so a course can be linked to it later. enrolledCourse? is optional because a course might not have been chosen yet.
You should see
Nandar Swift Basics