0
0
Swiftprogramming~30 mins

Built-in property wrappers (@State, @Published) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Built-in Property Wrappers @State and @Published in Swift
📖 Scenario: You are building a simple SwiftUI app that tracks a user's name and shows it on the screen. You will learn how to use @State to store local state in a view and @Published to notify changes in a data model.
🎯 Goal: Create a SwiftUI app with a text field to enter a name and a label that updates automatically when the name changes. Use @State for the text field input and @Published in a model class to broadcast changes.
📋 What You'll Learn
Create a SwiftUI view with a @State variable called name initialized to an empty string.
Create a class called UserModel that conforms to ObservableObject.
Add a @Published property called userName of type String initialized to an empty string in UserModel.
Bind the text field to the @State variable name.
Update the userName property of UserModel whenever name changes.
Display the userName from UserModel in a Text view that updates automatically.
💡 Why This Matters
🌍 Real World
This project shows how to manage and share state in SwiftUI apps, which is essential for building interactive user interfaces that respond to user input.
💼 Career
Understanding <code>@State</code> and <code>@Published</code> is important for iOS developers working with SwiftUI to create responsive and maintainable apps.
Progress0 / 4 steps
1
Create a SwiftUI view with a @State variable
Create a SwiftUI struct called ContentView that conforms to View. Inside it, create a @State variable called name and set it to an empty string "".
Swift
Need a hint?

Use @State var name: String = "" inside the ContentView struct.

2
Create a UserModel class with @Published property
Create a class called UserModel that conforms to ObservableObject. Inside it, add a @Published property called userName of type String initialized to an empty string "".
Swift
Need a hint?

Use class UserModel: ObservableObject and @Published var userName: String = "".

3
Bind the text field to @State and update UserModel
Inside ContentView, create an instance of UserModel called userModel using @StateObject. Replace the Text view with a TextField bound to the name variable. Add a .onChange modifier on name to update userModel.userName whenever name changes.
Swift
Need a hint?

Use @StateObject to create userModel. Bind TextField to $name. Use .onChange(of: name) to update userModel.userName.

4
Display the userName from UserModel
Below the TextField in ContentView, add a Text view that shows the text "User name is: " followed by the value of userModel.userName. This text should update automatically when userName changes.
Swift
Need a hint?

Use a Text view with "User name is: \(userModel.userName)" inside a VStack below the TextField.