Skip to content

Instantly share code, notes, and snippets.

@AliSoftware
Created June 14, 2019 21:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AliSoftware/00fc5e690adbf78a09ddb27d2dc66aa6 to your computer and use it in GitHub Desktop.
Save AliSoftware/00fc5e690adbf78a09ddb27d2dc66aa6 to your computer and use it in GitHub Desktop.
// Xcode 11b1
@propertyDelegate
struct Clamped<Value: Comparable> {
private var storage: Value
private var clamp: (Value) -> Value
init(min: Value, max: Value, initialValue: Value) {
let clampingFunction = { ($0...$0).clamped(to: min...max).lowerBound }
self.storage = clampingFunction(initialValue)
self.clamp = clampingFunction
}
var value: Value {
get { storage }
set {
self.storage = clamp(newValue)
}
}
}
extension Clamped where Value: FixedWidthInteger {
init(min: Value, initialValue: Value) {
self.init(min: min, max: Value.max, initialValue: initialValue)
}
init(max: Value, initialValue: Value) {
self.init(min: Value.min, max: max, initialValue: initialValue)
}
}
struct Example: CustomStringConvertible {
/// Soon possible after beta1:
// @Clamped(min: 0)
// var positive: Int = 0
/// In the meantime:
@Clamped(min: 0, initialValue: 0)
var positive: Int
@Clamped(min: 10, max: 20, initialValue: 0)
var tenToTwenty: Int
@Clamped(min: -1.0, max: +1.0, initialValue: 0)
var adjustment: Double
var description: String {
"""
positive: \(positive)
tenToTwenty: \(tenToTwenty)
adjustment: \(adjustment)
"""
}
}
var ex = Example()
print(ex)
ex.positive = -4
ex.tenToTwenty = 15
ex.adjustment = 0.5
print(ex)
ex.positive = +7
ex.tenToTwenty = 25
ex.adjustment = -2.5
print(ex)
@AliSoftware
Copy link
Author

Improvement idea: directly take a Range as parameter instead of min/max

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment