0
0
iOS Swiftmobile~5 mins

Model definition with @Model in iOS Swift

Choose your learning style9 modes available
Introduction

We use @Model to create simple data containers that hold information in our app. It helps keep data organized and easy to use.

When you want to store user information like name and age.
When you need to keep track of a list of items, like tasks or notes.
When you want to share data between different parts of your app.
When you want to save data that can change and update the UI automatically.
Syntax
iOS Swift
@Model
struct ModelName {
  var property1: Type
  var property2: Type
}

The @Model attribute tells Swift that this struct is a data model.

Properties inside the model hold the data you want to store.

Examples
This defines a user model with a name and age.
iOS Swift
@Model
struct User {
  var name: String
  var age: Int
}
This defines a task model with a title and a done status.
iOS Swift
@Model
struct Task {
  var title: String
  var isDone: Bool
}
Sample App

This app shows a simple user model with name and age displayed on screen.

iOS Swift
import SwiftUI

@Model
struct User {
  var name: String
  var age: Int
}

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

  var body: some View {
    VStack(spacing: 20) {
      Text("Name: \(user.name)")
      Text("Age: \(user.age)")
    }
    .padding()
  }
}
OutputSuccess
Important Notes

Use @Model to make your data easy to manage and update.

Models help keep your app organized by separating data from views.

Summary

@Model marks a struct as a data container.

Models hold properties that store your app's data.

Using models makes your app easier to build and maintain.