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

后端 未结 8 1240
梦谈多话
梦谈多话 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 16:02

    The shortest (but maybe not most efficient) way to clamp, is:

    let clamped = [0, a, 5].sorted()[1]
    

    Source: user tobr in a discussion on Hacker News

    0 讨论(0)
  • 2020-12-02 16:03

    With Swift 5.1, the idiomatic way to achieve the desired clamping would be with property wrappers. A touched-up example from NSHipster:

    @propertyWrapper
    struct Clamping<Value: Comparable> {
      var value: Value
      let range: ClosedRange<Value>
    
      init(wrappedValue: Value, _ range: ClosedRange<Value>) {
        precondition(range.contains(wrappedValue))
        self.value = wrappedValue
        self.range = range
      }
    
      var wrappedValue: Value {
        get { value }
        set { value = min(max(range.lowerBound, newValue), range.upperBound) }
      }
    }
    

    Usage:

    @Clamping(0...5) var a: Float = 4.2
    @Clamping(0...5) var b: Float = -1.3
    @Clamping(0...5) var c: Float = 6.4
    
    0 讨论(0)
提交回复
热议问题