Property wrappers help you write less repeated code by handling common tasks automatically for your properties.
0
0
Why property wrappers reduce boilerplate in Swift
Introduction
When you want to add the same behavior to many properties without rewriting code.
When you need to validate or transform property values consistently.
When you want to keep your code clean and easy to read by hiding repetitive logic.
When you want to add features like default values, logging, or data storage to properties easily.
Syntax
Swift
@propertyWrapper struct WrapperName { private var value: Type var wrappedValue: Type { get { value } set { value = newValue } } init(wrappedValue: Type) { self.value = wrappedValue } }
The @propertyWrapper keyword defines a reusable wrapper around a property.
The wrappedValue property controls how the wrapped property behaves.
Examples
This wrapper automatically capitalizes any string assigned to the property.
Swift
@propertyWrapper struct Capitalized { private var value: String = "" var wrappedValue: String { get { value } set { value = newValue.capitalized } } init(wrappedValue: String) { self.wrappedValue = wrappedValue } }
Using the
@Capitalized wrapper reduces the need to write capitalization code every time.Swift
struct User { @Capitalized var name: String } var user = User(name: "john") print(user.name) // Prints "John"
Sample Program
This program uses a property wrapper to automatically remove spaces around the text, so you don't have to write trimming code each time.
Swift
@propertyWrapper struct Trimmed { private var value: String = "" var wrappedValue: String { get { value } set { value = newValue.trimmingCharacters(in: .whitespacesAndNewlines) } } init(wrappedValue: String) { self.wrappedValue = wrappedValue } } struct Message { @Trimmed var text: String } var msg = Message(text: " Hello Swift! ") print("'\(msg.text)'" )
OutputSuccess
Important Notes
Property wrappers keep your code DRY (Don't Repeat Yourself) by centralizing common logic.
You can reuse property wrappers across many properties and types.
They make your code easier to maintain and understand.
Summary
Property wrappers reduce repeated code by wrapping common property behaviors.
They help keep your code clean and consistent.
Using them makes adding features to properties simple and reusable.