首页 > 解决方案 > 从最接近但小于另一个值的数组中获取值

问题描述

我有以下数组:

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
}

标签: swift

解决方案


推荐阅读