This program shows two property wrappers combined. The health property is clamped between 0 and 100, and changes are logged.
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)
}
}
@propertyWrapper
struct Logged {
private var storage: Clamped
var wrappedValue: Int {
get { storage.wrappedValue }
set {
let oldValue = storage.wrappedValue
storage.wrappedValue = newValue
print("Changing value from \(oldValue) to \(storage.wrappedValue)")
}
}
init(wrappedValue: Int) {
self.storage = Clamped(wrappedValue: wrappedValue, min: 0, max: 100)
}
init(wrappedValue: Clamped) {
self.storage = wrappedValue
}
}
struct Player {
@Logged @Clamped(min: 0, max: 100) var health: Int = 50
}
var player = Player()
player.health = 120
player.health = -10
player.health = 80