“夹紧"的标准方式Swift 中两个值之间的数字 [英] Standard way to "clamp" a number between two values in Swift

查看:22
本文介绍了“夹紧"的标准方式Swift 中两个值之间的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定:

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

我想知道将这些值限制在给定范围内的最简单、最快捷的方法,例如 0...5,例如:

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

a -> 4.2
b -> 0
c -> 5

我知道我可以做到以下几点:

I know I can do the following:

let clamped = min(max(a, 0), 5)

或者类似的东西:

let clamped = (a < 0) ? 0 : ((a > 5) ? 5 : a)

但我想知道在 Swift 中是否还有其他方法可以做到这一点——特别是,我想知道(以及关于 SO 的文档,因为在 Swift 中似乎没有关于钳位数字的问题)是否有是 Swift 标准库中专门用于此目的的任何内容.

But I was wondering if there were any other ways to do this in Swift—in particular, I want to know (and document on SO, since there doesn't appear to be a question about clamping numbers in Swift) whether there is anything in the Swift standard library intended specifically for this purpose.

可能没有,如果有,那也是我很乐意接受的答案.

There may not be, and if so, that's also an answer I'll happily accept.

推荐答案

Swift 4/5

Comparable/Strideable 的扩展类似于 ClosedRange.clamped(to:_) ->ClosedRange 来自标准 Swift 库.

Extension of Comparable/Strideable similar to ClosedRange.clamped(to:_) -> ClosedRange from standard Swift library.

extension Comparable {
    func clamped(to limits: ClosedRange<Self>) -> Self {
        return min(max(self, limits.lowerBound), limits.upperBound)
    }
}

// Swift < 5.1
extension Strideable where Stride: SignedInteger {
    func clamped(to limits: CountableClosedRange<Self>) -> Self {
        return min(max(self, limits.lowerBound), limits.upperBound)
    }
}

用法:

15.clamped(to: 0...10) // returns 10
3.0.clamped(to: 0.0...10.0) // returns 3.0
"a".clamped(to: "g"..."y") // returns "g"

// this also works (thanks to Strideable extension)
let range: CountableClosedRange<Int> = 0...10
15.clamped(to: range) // returns 10

这篇关于“夹紧"的标准方式Swift 中两个值之间的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆