SwiftMidMCQ
What is `@propertyWrapper` and how do you create one?
Test your knowledge:
Explanation & Code
Answer:
A property wrapper adds custom logic around getting and setting a property. SwiftUI's @State, @Binding, and @Published are all property wrappers.
Code Example:
@propertyWrapper
struct Clamped {
private var value: Int
let range: ClosedRange<Int>
var wrappedValue: Int {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
init(wrappedValue: Int, _ range: ClosedRange<Int>) {
self.range = range
self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
}
struct Player {
@Clamped(0...100) var health: Int = 100
}
var player = Player()
player.health = 150 // clamped to 100
player.health = -10 // clamped to 0
Rate your understanding: