@propertyWrapper struct RangeValid<Value: Comparable> { private var _min: Value? private var _max: Value? private var _value: Value private(set) var projectedValue: Bool
init(wrappedValue: Value, min: Value? = nil, max: Value? = nil) { self._min = min self._max = max self._value = wrappedValue
adjust(value: wrappedValue) } var wrappedValue: Value { get { return self._value } set { update(value: newValue) } }
private func adjust(value newValue: Value) { if let min = _min, newValue < min { self._value = min projectedValue = false } else if let max = _max, newValue > max { self._value = max projectedValue = false } else { self._value = newValue projectedValue = true } } }
struct TestStructure { @RangeValid(min: 1, max: 100) var score: Int = 60 }
let test = TestStructure() print(test.score) // 60 print(test.$score) // true