What if you could add smart behavior to any variable with just one simple annotation?
Why @propertyWrapper declaration in Swift? - Purpose & Use Cases
Imagine you have many variables in your Swift code that need the same special behavior, like always keeping a value within a range or logging changes. You write the same code again and again for each variable.
This manual way is slow and boring. You might forget to add the special behavior somewhere, or make mistakes copying the code. It becomes hard to fix or change later because the code is repeated everywhere.
The @propertyWrapper lets you write that special behavior once and then reuse it easily by just adding a simple annotation. It keeps your code clean, safe, and easy to update.
var score: Int = 0 { didSet { if score < 0 { score = 0 } if score > 100 { score = 100 } } }
@propertyWrapper
struct Clamped {
private var value: Int
private let range: ClosedRange<Int>
init(wrappedValue: Int, _ range: ClosedRange<Int>) {
self.range = range
self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
var wrappedValue: Int {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
}
@Clamped(0...100) var score: Int = 0You can create reusable, clean, and safe property behaviors that make your code easier to write and maintain.
For example, you can create a property wrapper to automatically save user settings to disk whenever they change, without repeating save code everywhere.
Manual repetition of property behavior is error-prone and hard to maintain.
@propertyWrapper lets you write reusable property logic once.
This makes your Swift code cleaner, safer, and easier to update.