0
0
Swiftprogramming~30 mins

Composing property wrappers in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Composing property wrappers
📖 Scenario: Imagine you are building a simple app that tracks user settings. You want to create reusable property wrappers to add behaviors like capitalizing strings and trimming whitespace. Then, you want to combine these wrappers to apply both behaviors to a single property.
🎯 Goal: Build two property wrappers: Capitalized and Trimmed. Then compose them to create a property that is both trimmed and capitalized automatically.
📋 What You'll Learn
Create a property wrapper called Capitalized that capitalizes the wrapped string value.
Create a property wrapper called Trimmed that trims whitespace from the wrapped string value.
Compose the two wrappers so a property is first trimmed then capitalized.
Print the final value of the composed property to verify the behavior.
💡 Why This Matters
🌍 Real World
Property wrappers are used in Swift apps to add reusable behaviors like validation, formatting, or storage management to properties without repeating code.
💼 Career
Understanding property wrappers and how to compose them is valuable for Swift developers working on clean, maintainable codebases, especially in iOS app development.
Progress0 / 4 steps
1
Create the Capitalized property wrapper
Create a property wrapper called Capitalized with a wrappedValue of type String. In the wrappedValue setter, update the value to be capitalized using capitalized property.
Swift
Need a hint?

Use @propertyWrapper before the struct. Store the value privately. Use capitalized to change the string.

2
Create the Trimmed property wrapper
Create a property wrapper called Trimmed with a wrappedValue of type String. In the wrappedValue setter, update the value by trimming whitespace using trimmingCharacters(in: .whitespacesAndNewlines).
Swift
Need a hint?

Similar to Capitalized, but use trimmingCharacters(in: .whitespacesAndNewlines) to remove spaces.

3
Compose the property wrappers on a property
Create a struct called UserSettings with a property username of type String. Apply the @Capitalized and @Trimmed wrappers to username so that trimming happens first, then capitalization.
Swift
Need a hint?

Apply @Capitalized before @Trimmed on the username property.

4
Print the composed property value
Create an instance of UserSettings with username initialized to " hello world ". Then print the username property to see the trimmed and capitalized result.
Swift
Need a hint?

Initialize UserSettings with the string containing spaces. Printing username should show trimmed and capitalized text.