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

后端 未结 8 1255
梦谈多话
梦谈多话 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:55

    Following up on @Fattie's answer and my comment, here's my suggestion for clarity:

    extension Comparable {
        func clamped(_ a: Self, _ b: Self) -> Self {
            max(min(self, a), b)
        }
    }
    

提交回复
热议问题