Swift·Swift from optionals to SwiftUI

Structs and classes

Choose value types by default and use classes for identity.

Beginner 13 min read Lesson 4 of 300 Challenge included
What you will be able to do
  • Prefer structs for models and UI.
  • Use classes for identity or shared mutable state.
  • Use initializers to enforce invariants.
  • Mark UI-facing types as @MainActor when needed.

In plain English

Structs are value types with copied semantics; classes are reference types with identity. SwiftUI strongly prefers structs. Use classes when shared identity or inheritance is genuinely required.

Models.swiftSwift
struct Lesson: Identifiable {
    let id: UUID
    var title: String
    var minutes: Int
}

final class Store {
    private(set) var lessons: [Lesson] = []
    func add(_ lesson: Lesson) { lessons.append(lesson) }
}
Your turn

Make a model identifiable

Easy

Make a Lesson struct conform to Identifiable.

SWIFT · starter
struct Lesson {
Check your understanding before moving on.
Knowledge checkQuestion 1

What happens when a struct is assigned to another variable?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 4 of 300 · 0% of course