MasterOnce
HomeBlogHow-To
3 min readMar 6, 2026
Swift

How to Create a Property Wrapper

Wrap common logic in a reusable property wrapper.

Steps

  1. Paste the code into a Swift file or playground.
  2. Run it once to verify the output.
  3. Adjust the inputs to match your use case.

Copy and paste

import Foundation

@propertyWrapper
struct Clamped {
    private var value: Int
    let range: ClosedRange<Int>

    init(wrappedValue: Int, _ range: ClosedRange<Int>) {
        self.range = range
        self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
    }

    var wrappedValue: Int {
        get { value }
        set { value = min(max(newValue, range.lowerBound), range.upperBound) }
    }
}

struct Settings {
    @Clamped(0...100) var volume: Int = 120
}

print(Settings().volume)

Notes

  • Keep functions small and focused for reuse.
  • Prefer safe APIs like optionals and guards.