Skip to content

Instantly share code, notes, and snippets.

@heestand-xyz
Created June 12, 2020 07:09
Show Gist options
  • Save heestand-xyz/7a2ed64b305a8e9c8408e8f831082b68 to your computer and use it in GitHub Desktop.
Save heestand-xyz/7a2ed64b305a8e9c8408e8f831082b68 to your computer and use it in GitHub Desktop.
Swift - Property Wrapper - Clamped Value
@propertyWrapper
struct ClampedValue<F: FloatingPoint> {
var value: F
let min: F?
let max: F?
init(wrappedValue: F, min: F? = nil, max: F? = nil) {
value = wrappedValue
self.min = min
self.max = max
}
var wrappedValue: F {
set { value = newValue }
get {
var value: F = self.value
if let min: F = min {
if value < min {
value = min
}
}
if let max: F = max {
if value > max {
value = max
}
}
return value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment