Clamped

將變數限制在指定的範圍 (ClosedRange) 裡面。

@propertyWrapper
public struct Clamped<T: Comparable> {
    
    private var _value: T
    private let _range: ClosedRange<T>
    
    public init(wrappedValue: T, in range: ClosedRange<T>) {
        self._value = wrappedValue.clamped(in: range)
        self._range = range
    }
    
    public var wrappedValue: T {
        get { _value }
        set { _value = newValue.clamped(in: _range) }
    }
}

Last updated