What if you could track changes to your data automatically without writing extra code everywhere?
Why WrappedValue and projectedValue in Swift? - Purpose & Use Cases
Imagine you have a box that holds a value, and you want to keep track of that value and also some extra info about it, like whether it has changed or not. Without special tools, you would have to write extra code everywhere to manage both the value and its extra info.
Manually writing code to handle both the main value and its extra info is slow and easy to mess up. You might forget to update the extra info or mix up the value and the extra info, causing bugs and confusion.
Using wrappedValue and projectedValue in Swift property wrappers lets you keep the main value and extra info together cleanly. You access the main value simply, and the extra info through a special property, making your code neat and less error-prone.
var name: String
var nameChanged: Bool = false
func updateName(newName: String) {
name = newName
nameChanged = true
}@propertyWrapper
struct TrackChange {
private var value: String = ""
private var changed: Bool = false
var wrappedValue: String {
get { value }
set { value = newValue; changed = true }
}
var projectedValue: Bool { changed }
}
@TrackChange var name: StringThis lets you write cleaner code that automatically tracks extra info about values without extra manual work.
In a form app, you can track if a user changed a field by using wrappedValue for the field's text and projectedValue to know if it was edited, helping you enable or disable the save button.
wrappedValue holds the main value you work with.
projectedValue holds extra info related to that value.
Using both keeps your code simple and less error-prone.