0
0
Swiftprogramming~30 mins

@propertyWrapper declaration in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @propertyWrapper to Manage User Age
📖 Scenario: You are building a simple user profile system where you want to control how the user's age is stored and validated.
🎯 Goal: Create a @propertyWrapper called AgeLimit that ensures the age is always between 0 and 120. Then use it in a User struct to store the user's age safely.
📋 What You'll Learn
Create a @propertyWrapper named AgeLimit
Inside AgeLimit, have a private variable value of type Int
Initialize value with a default age passed in the initializer
Clamp the age value between 0 and 120 in the wrappedValue property
Create a struct User with a property age using the @AgeLimit wrapper
Initialize a User instance with an age and print the age
💡 Why This Matters
🌍 Real World
Property wrappers help keep data clean and safe by controlling how values are stored and changed, useful in apps with user input.
💼 Career
Understanding property wrappers is important for Swift developers to write clean, reusable, and safe code in iOS and macOS apps.
Progress0 / 4 steps
1
Create the @propertyWrapper AgeLimit with a private value
Create a @propertyWrapper named AgeLimit with a private variable value of type Int initialized to 0.
Swift
Need a hint?

Use @propertyWrapper before the struct declaration. Inside, declare private var value: Int = 0.

2
Add initializer to AgeLimit to set initial age value
Add an initializer to AgeLimit that takes an Int parameter called wrappedValue and sets value to it.
Swift
Need a hint?

Write init(wrappedValue: Int) and assign wrappedValue to value.

3
Implement wrappedValue property to clamp age between 0 and 120
Add a computed property wrappedValue of type Int that returns value clamped between 0 and 120. When setting, update value with the clamped new value.
Swift
Need a hint?

Use a computed property with get and set. Clamp values using conditional expressions.

4
Create User struct using @AgeLimit and print age
Create a struct User with a property age using the @AgeLimit wrapper. Initialize a User instance with age 150 and print user.age.
Swift
Need a hint?

Define User with @AgeLimit var age: Int. Create user with age 150 and print user.age.