3 min readMar 6, 2026
SwiftHow to Create a Property Wrapper
Wrap common logic in a reusable property wrapper.
Steps
- Paste the code into a Swift file or playground.
- Run it once to verify the output.
- 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.
