How do I use property observers in Swift?
Property observers in Swift are a powerful feature that allows you to observe and respond to changes in property values. They provide a way to add custom code before or after a property’s value changes, enabling you to perform actions such as validation, triggering updates, or logging. Property observers are available for both stored properties and computed properties.
Here’s how you can use property observers in Swift:
- `willSet` Property Observer: The `willSet` observer is called just before the value of a property is set. It provides you with the new value using the default parameter name `newValue`. You can use this observer to perform tasks or validation before the property is updated.
```swift var score: Int = 0 { willSet { if newValue > 100 { print("Score cannot exceed 100.") } } } ```
- `didSet` Property Observer: The `didSet` observer is called immediately after the value of a property has been updated. It provides access to the old value using the default parameter name `oldValue`. You can use this observer to respond to property changes, update UI, or trigger other actions.
```swift var username: String = "" { didSet { if username.isEmpty { username = "Guest" } } } ```
- Computed Property with Observers: You can also use property observers with computed properties by providing both `get` and `set` implementations along with observers. This allows you to add custom behavior when getting or setting the computed property.
```swift var fullName: String { get { return "\(firstName) \(lastName)" } set { let parts = newValue.split(separator: " ") firstName = String(parts.first ?? "") lastName = String(parts.last ?? "") } didSet { print("Full name changed to \(fullName)") } } ```
Property observers are a valuable tool for maintaining data consistency and ensuring that your code responds appropriately to property changes. They are especially useful in user interface updates, data validation, and managing the behavior of your objects when properties are modified.