Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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

This comment has been minimized.

Copy link
Owner Author

@AliSoftware AliSoftware commented Jun 14, 2019

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