0
0
Swiftprogramming~30 mins

WrappedValue and projectedValue in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using WrappedValue and projectedValue in Swift Property Wrappers
📖 Scenario: Imagine you are building a simple app that tracks the progress of tasks. You want to create a custom property wrapper that stores a task's progress as a percentage and also provides a message about the progress.
🎯 Goal: Build a Swift program that uses a property wrapper with wrappedValue to store the progress percentage and projectedValue to provide a progress message.
📋 What You'll Learn
Create a property wrapper named ProgressTracker with wrappedValue and projectedValue
Use wrappedValue to store an integer progress percentage
Use projectedValue to return a string message about the progress
Create a struct Task with a property progress using the ProgressTracker wrapper
Print the progress percentage and the progress message
💡 Why This Matters
🌍 Real World
Property wrappers help you add reusable behavior to properties, such as validation, formatting, or extra info, which is common in app development.
💼 Career
Understanding property wrappers and their wrapped and projected values is important for Swift developers working on iOS or macOS apps to write clean and reusable code.
Progress0 / 4 steps
1
Create the ProgressTracker property wrapper
Create a property wrapper named ProgressTracker with a wrappedValue property of type Int initialized to 0.
Swift
Need a hint?

Use @propertyWrapper before the struct. Define wrappedValue as an Int with default 0.

2
Add projectedValue to provide a progress message
Inside ProgressTracker, add a computed property projectedValue of type String that returns "Progress is X%" where X is the current wrappedValue.
Swift
Need a hint?

Define projectedValue as a computed property returning a string with the current wrappedValue.

3
Create Task struct using ProgressTracker
Create a struct named Task with a property progress that uses the @ProgressTracker property wrapper.
Swift
Need a hint?

Define struct Task with a property progress using @ProgressTracker.

4
Set progress and print wrappedValue and projectedValue
Create an instance of Task named myTask. Set myTask.progress to 75. Then print myTask.progress and myTask.$progress.
Swift
Need a hint?

Create myTask, assign 75 to progress, then print myTask.progress and myTask.$progress.