Property wrappers let you add extra behavior to variables easily. Configuring them means you can customize how they work for each use.
Property wrappers with configuration in Swift
@propertyWrapper struct WrapperName { var wrappedValue: Type init(wrappedValue: Type, configParam: ConfigType) { // use configParam to customize behavior self.wrappedValue = wrappedValue } }
The init(wrappedValue:configParam:) lets you pass extra settings when you use the wrapper.
You use the wrapper by adding @WrapperName(configParam: value) before a variable.
score between 0 and 10 using the Clamped wrapper with configuration.@Clamped(min: 0, max: 10) var score: Int = 5
Clamped wrapper that keeps a number inside a range given by min and max.import Foundation @propertyWrapper struct Clamped { private var value: Int let min: Int let max: Int var wrappedValue: Int { get { value } set { value = Swift.min(Swift.max(newValue, min), max) } } init(wrappedValue: Int, min: Int, max: Int) { self.min = min self.max = max self.value = Swift.min(Swift.max(wrappedValue, min), max) } }
This program uses a Clamped property wrapper with configuration to keep health and level inside set ranges. When we try to set values outside the range, they get clamped back inside.
import Foundation @propertyWrapper struct Clamped { private var value: Int let min: Int let max: Int var wrappedValue: Int { get { value } set { value = Swift.min(Swift.max(newValue, min), max) } } init(wrappedValue: Int, min: Int, max: Int) { self.min = min self.max = max self.value = Swift.min(Swift.max(wrappedValue, min), max) } } struct Player { @Clamped(min: 0, max: 100) var health: Int = 50 @Clamped(min: 1, max: 10) var level: Int = 1 } var player = Player() print("Initial health: \(player.health)") print("Initial level: \(player.level)") player.health = 150 player.level = 0 print("After setting health to 150: \(player.health)") print("After setting level to 0: \(player.level)")
Property wrappers with configuration let you reuse code but customize it for each variable.
Use descriptive names for configuration parameters to make your code easy to read.
Remember to handle the initial value inside the wrapper's initializer to apply the configuration right away.
Property wrappers add extra behavior to variables.
Configuration parameters let you customize that behavior per use.
This helps keep your code clean and reusable.