swiftintegernsarraycgfloat

Swift: Check which value in NSArray is closest to another given value


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.


Solution

  • Save the minimumDifference as a variable.

    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...