Property Wrapper in Swift
Level 5551 keystrokes
The Clamped property wrapper keeps an Int inside a range, both at initialization and on every assignment. Setting health to 150 stores 100 and setting level to -5 stores 0, so it prints Health: 100, Level: 0.
Swift code
// Marks the struct as a property wrapper usable as @Clamped1@propertyWrapper2struct Clamped { // The actual stored value and the allowed range3 var value: Int4 let range: ClosedRange<Int>5 // wrappedValue is what player.health reads and writes6 var wrappedValue: Int {7 get { value } // Clamps every new value: below the range → lowerBound, above → upperBound8 set { value = min(max(newValue, range.lowerBound), range.upperBound) }9 }10 // Receives the initial value (= 100) and the range from @Clamped(0...100)11 init(wrappedValue: Int, _ range: ClosedRange<Int>) {12 self.range = range // The initial value is clamped too13 self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)14 }15}16 17struct Player { // health stays within 0...10018 @Clamped(0...100) var health: Int = 100 // level stays within 0...1019 @Clamped(0...10) var level: Int = 120}21 22var player = Player()// 150 is above the range, so 100 is stored23player.health = 150// -5 is below the range, so 0 is stored24player.level = -5// Prints Health: 100, Level: 025print("Health: \(player.health), Level: \(player.level)")Output
Health: 100, Level: 0
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Swift code and how often they appear.
.× 16(× 11)× 11:× 9=× 8,× 6{× 6}× 6@× 3"× 2