问题描述
让我说我有一个数组
var values:[CGFloat] = [-12.0, 450, 300]
我需要找出这些数字中的哪个最接近给定值,例如
I need to find out which of these numbers is closest to a given value, say
var givenValue:CGFloat = 64
有没有一种有效的方法来找出数组中哪个对象最接近64?
我知道您可以执行以下操作:
Is there an efficient way to find out which object in the array is closest to 64?
I know you can do something like this:
if abs(values[0] - 64) < abs(values[1] - 64) && abs(values[0] - 64) < abs(values[2] - 64) {
println("values[0] is the closest to 64)
}
但是,这将导致多个if语句,并且效率很低.
But this will result in several if-statements and seems inefficient.
有人知道更好的方法吗?在此示例中,我将需要数组中的值以及它在数组中的哪个objectIndex.
Does anyone know a better way to do this? In this example I would need the value in the array as well as which objectIndex in the array it is.
推荐答案
将minimumDifference
另存为变量.
然后迭代数组.每次将数组中值的差异与最小差异进行比较.
Then iterate the array. Each time compare the difference in the value from the array to the minimum difference.
如果新差异较小,则换出最小差异.
If the new difference is smaller then swap out the minimu difference.
在数组末尾,您将拥有最小的差异.
At the end of the array you will have the minimum difference.
这与找到最大值,最小值等...
This is the same as finding the highest value, smallest value, etc...
这篇关于Swift:检查NSArray中哪个值最接近另一个给定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!