从最接近但小于另一个值的数组中获取值

时间:2019-07-16 04:16:00

标签: swift

我有以下数组:

let array = [0.0, 4.5, 5.6, 16.4, 16.7]

给出一个随机数,找出数组中哪个值小于但最接近。

示例

Value = 5.5 //result should be 4.5 from array
Value = 5.7 //result should be 5.6 from array
Value = 0.1 //result should be 0.0 from array
Value = 200.0 //result should be 16.7 from array

到目前为止,我有这段代码可以测试很大的数字,但不能测试最接近的较小数字

var resultNext = 100.0
if let nextResult = self.pointDataForActivity.first(where: { $0 > Value }) {
print("The first greater number is \(nextResult).")
resultNext = nextResult
}

0 个答案:

没有答案