Bird
Raised Fist0
iOS Swiftmobile~20 mins

Model definition with @Model in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: User Profile Screen
This screen shows a user's profile information using a model defined with @Model. It displays the user's name and age.
Target UI
-------------------------
|      User Profile      |
|-----------------------|
| Name:                 |
|                       |
| Age:                  |
|                       |
|                       |
|                       |
-------------------------
Define a User model using @Model with properties: name (String) and age (Int).
Create a SwiftUI view that shows the user's name and age.
Initialize the User model with sample data and display it on the screen.
Starter Code
iOS Swift
import SwiftUI
import SwiftData

// TODO: Define the User model here using @Model

struct UserProfileView: View {
    // TODO: Create a @StateObject or @ObservedObject for User model

    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("Name:")
            Text("") // TODO: Show user's name here
            Text("Age:")
            Text("") // TODO: Show user's age here
            Spacer()
        }
        .padding()
        .navigationTitle("User Profile")
    }
}

struct UserProfileView_Previews: PreviewProvider {
    static var previews: some View {
        UserProfileView()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI
import SwiftData

@Model
class User {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

struct UserProfileView: View {
    @StateObject private var user = User(name: "Alice", age: 30)

    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("Name:")
                .font(.headline)
            Text(user.name)
                .font(.title2)
            Text("Age:")
                .font(.headline)
            Text(String(user.age))
                .font(.title2)
            Spacer()
        }
        .padding()
        .navigationTitle("User Profile")
    }
}

struct UserProfileView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            UserProfileView()
        }
    }
}

We define the User model class with the @Model attribute from SwiftData. This tells Swift that this class is a data model suitable for persistence and observation.

The User class has two properties: name (a String) and age (an Int), initialized via the constructor.

In the UserProfileView, we create a @StateObject instance of User with sample data (name "Alice" and age 30). This allows the view to observe changes to the model.

The view displays the user's name and age using Text views with some styling for clarity.

Wrapping the preview in a NavigationView shows the navigation title properly.

Final Result
Completed Screen
-------------------------
|      User Profile      |
|-----------------------|
| Name:                 |
| Alice                 |
| Age:                  |
| 30                    |
|                       |
|                       |
-------------------------
The screen shows the user's name and age clearly.
No interactive elements on this screen; it is a simple display.
If the user model changes, the UI would update automatically.
Stretch Goal
Add a button to increase the user's age by 1 when tapped.
💡 Hint
Add a Button below the age text that updates the user.age property inside an action closure.

Practice

(1/5)
1. What is the main purpose of using @Model in SwiftUI?
easy
A. To mark a class as a data container for app state
B. To create a user interface element
C. To define a function for navigation
D. To style text in the app

Solution

  1. Step 1: Understand the role of @Model

    @Model is used to mark a class that holds data for the app, making it a data container.
  2. Step 2: Differentiate from UI or styling

    @Model does not create UI elements or style text; it only defines data structures.
  3. Final Answer:

    To mark a class as a data container for app state -> Option A
  4. Quick Check:

    @Model = data container [OK]
Hint: Remember: @Model is for data, not UI or styling [OK]
Common Mistakes:
  • Thinking @Model creates UI components
  • Confusing @Model with styling attributes
  • Assuming @Model defines functions
2. Which of the following is the correct syntax to define a model class with @Model in Swift?
easy
A. class User { @Model var name: String }
B. class @Model User { var name: String }
C. class User @Model { var name: String }
D. @Model class User { var name: String }

Solution

  1. Step 1: Recall correct @Model placement

    @Model is placed before the class keyword to mark the entire class as a model.
  2. Step 2: Check other options for syntax errors

    Other placements of @Model cause syntax errors.
  3. Final Answer:

    @Model class User { var name: String } -> Option D
  4. Quick Check:

    @Model before class = correct syntax [OK]
Hint: Put @Model right before class keyword [OK]
Common Mistakes:
  • Placing @Model after class name
  • Adding @Model before property instead of class
  • Using @Model inside class body
3. Given the model definition:
@Model class Task { var title: String; var done: Bool }

What is the output of this code?
let task = Task(title: "Buy milk", done: false)
print(task.done)
medium
A. true
B. false
C. nil
D. Compilation error

Solution

  1. Step 1: Understand model initialization

    The Task model is initialized with done set to false (@Model synthesizes the initializer).
  2. Step 2: Print the done property value

    Printing task.done outputs the Boolean value false.
  3. Final Answer:

    false -> Option B
  4. Quick Check:

    task.done = false [OK]
Hint: Check property values passed during initialization [OK]
Common Mistakes:
  • Assuming default true value for done
  • Expecting nil instead of false
  • Thinking @Model changes property defaults
4. Identify the error in this model definition:
@Model class Product {
  var name: String
  var price: Double
  func discount() -> Double {
    return price * 0.9
  }
}
medium
A. No error, this is valid
B. Models cannot have functions inside them
C. price should be an Int, not Double
D. Missing initializer for properties

Solution

  1. Step 1: Check @Model class rules

    @Model classes are data containers that support stored properties, computed properties, initializers (synthesized), and methods.
  2. Step 2: Analyze potential issues

    No syntax errors: initializer synthesized by @Model, Double valid for price, methods allowed.
  3. Final Answer:

    No error, this is valid -> Option A
  4. Quick Check:

    @Model class = supports methods [OK]
Hint: @Model classes support methods [OK]
Common Mistakes:
  • Thinking @Model prohibits functions
  • Believing explicit initializer always required
  • Insisting price must be Int
5. You want to create a model to store user profile data with a name and optional age. Which is the best way to define it using @Model?
hard
A. @Model class UserProfile { var name: String; var age: Optional<Int> }
B. @Model class UserProfile { var name: String; var age: Int = nil }
C. @Model class UserProfile { var name: String; var age: Int? }
D. @Model class UserProfile { var name: String; var age: Int! }

Solution

  1. Step 1: Understand optional property syntax

    In Swift, optional properties are declared with a question mark, e.g., Int?.
  2. Step 2: Evaluate each option's correctness

    @Model class UserProfile { var name: String; var age: Int? } uses correct, idiomatic optional syntax. @Model class UserProfile { var name: String; var age: Int = nil } assigns nil to a non-optional Int, which is invalid. @Model class UserProfile { var name: String; var age: Optional<Int> } uses verbose Optional<Int>. @Model class UserProfile { var name: String; var age: Int! } uses implicitly unwrapped optional which is less safe.
  3. Final Answer:

    @Model class UserProfile { var name: String; var age: Int? } -> Option C
  4. Quick Check:

    Optional property = Int? [OK]
Hint: Use ? for optional properties in models [OK]
Common Mistakes:
  • Assigning nil to non-optional types
  • Using wrong optional syntax
  • Using implicitly unwrapped optionals unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard