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 @Clamped
1@propertyWrapper
2struct Clamped {
// The actual stored value and the allowed range
3 var value: Int
4 let range: ClosedRange<Int>
5
// wrappedValue is what player.health reads and writes
6 var wrappedValue: Int {
7 get { value }
// Clamps every new value: below the range → lowerBound, above → upperBound
8 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 too
13 self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
14 }
15}
16
17struct Player {
// health stays within 0...100
18 @Clamped(0...100) var health: Int = 100
// level stays within 0...10
19 @Clamped(0...10) var level: Int = 1
20}
21
22var player = Player()
// 150 is above the range, so 100 is stored
23player.health = 150
// -5 is below the range, so 0 is stored
24player.level = -5
// Prints Health: 100, Level: 0
25print("Health: \(player.health), Level: \(player.level)")

Output

Health: 100, Level: 0
Practice typing this code

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

More Swift examples at level 5

← Swift typing practice