Standard way to “clamp” a number between two values in Swift

后端 未结 8 1249
梦谈多话
梦谈多话 2020-12-02 15:10

Given:

let a = 4.2
let b = -1.3
let c = 6.4

I want to know the simplest, Swiftiest way to clamp these values to a given range, say 0...

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 15:37

    Using the same syntax as Apple to do the min and max operator:

    public func clamp(_ value: T, minValue: T, maxValue: T) -> T where T : Comparable {
        return min(max(value, minValue), maxValue)
    }
    

    You can use as that:

    let clamped = clamp(newValue, minValue: 0, maxValue: 1)
    

    The cool thing about this approach is that any value defines the necessary type to do the operation, so the compiler handles that itself.

提交回复
热议问题