Lets say I have an array
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
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)
}
But this will result in several if-statements and seems inefficient.
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.