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.