Junior — Middle
Is it possible to implement a custom property wrapper in Swift?
sobes.tech AI
Answer from AI
Yes, in Swift you can create custom property wrappers. These are special types that encapsulate the logic for accessing and storing a property's value.
Here's an example of a simple wrapper that limits a property's value to the range from 0 to 100:
@propertyWrapper
struct Clamped {
private var value: Int
private let range: ClosedRange<Int>
var wrappedValue: Int {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
init(wrappedValue initialValue: Int, _ range: ClosedRange<Int>) {
self.range = range
self.value = min(max(initialValue, range.lowerBound), range.upperBound)
}
}
struct Player {
@Clamped(0...100) var health: Int = 100
}
var player = Player()
player.health = 150
print(player.health) // Will output 100, as the value is limited
Thus, wrappers allow reusing and centralizing the logic for working with properties.