0
0
Swiftprogramming~3 mins

Why WrappedValue and projectedValue in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could track changes to your data automatically without writing extra code everywhere?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
var name: String
var nameChanged: Bool = false

func updateName(newName: String) {
  name = newName
  nameChanged = true
}
After
@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: String
What It Enables

This lets you write cleaner code that automatically tracks extra info about values without extra manual work.

Real Life Example

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.

Key Takeaways

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.