Created
June 14, 2019 21:50
-
-
Save AliSoftware/00fc5e690adbf78a09ddb27d2dc66aa6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improvement idea: directly take a
Range
as parameter instead ofmin
/max