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.