0
0
Swiftprogramming~30 mins

Property wrappers with configuration in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Property wrappers with configuration
📖 Scenario: Imagine you are building a simple app that tracks user settings. You want to make sure some settings have default values and can be easily configured.
🎯 Goal: You will create a property wrapper that allows setting a default value and then use it to manage user settings with configurable defaults.
📋 What You'll Learn
Create a property wrapper called DefaultValue that stores a wrapped value.
Add a configuration property called defaultValue to the wrapper.
Use the property wrapper on a struct's properties with different default values.
Print the values of the properties to see the defaults in action.
💡 Why This Matters
🌍 Real World
Property wrappers help manage default values and add behavior to properties in apps, making code cleaner and easier to maintain.
💼 Career
Understanding property wrappers is useful for Swift developers working on iOS or macOS apps to write reusable and configurable code.
Progress0 / 4 steps
1
Create the property wrapper with a default value
Create a property wrapper called DefaultValue that has a generic type Value. Inside it, declare a variable wrappedValue of type Value. Add an initializer that accepts a parameter called defaultValue of type Value and sets wrappedValue to this defaultValue.
Swift
Need a hint?

Use @propertyWrapper before the struct. The initializer should set wrappedValue to the defaultValue parameter.

2
Create a struct with properties using the wrapper
Create a struct called UserSettings. Inside it, declare two properties: username and isDarkMode. Use the @DefaultValue property wrapper on both. Set the default value for username to "Guest" and for isDarkMode to false.
Swift
Need a hint?

Use the property wrapper syntax @DefaultValue(defaultValue: ...) before each property.

3
Create an instance and access the properties
Create a variable called settings and assign it a new instance of UserSettings. Then, access the properties username and isDarkMode from settings.
Swift
Need a hint?

Create settings as UserSettings(). Access properties with dot notation like settings.username.

4
Print the property values
Print the values of settings.username and settings.isDarkMode using two separate print statements.
Swift
Need a hint?

Use print(settings.username) and print(settings.isDarkMode) to show the values.