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

有些话、适合烂在心里 提交于 2020-05-16 05:01:28

问题


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.


回答1:


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




回答2:


For completion's sake, I will post my final code that solved this

    //Array to hold dist. of visible cell to pt. 64
    var distancesToTop = [CGFloat]()

    //Array of visible cell indexPaths
    var indexPaths = tableView.indexPathsForVisibleRows()!

    for visibleCell in tableView.visibleCells() { //for each visible cell...

        //Append distance to 64 to the array
        distancesToTop.append(abs((visibleCell.frame.minY - tableView.contentOffset.y) - 64))

    }

    //Find the lowest of those values
    let numMin = distancesToTop.reduce(CGFloat.max, { min($0, $1) })

    //Determine the objectForIndexPath that the minimum number was in
    let num = find(distancesToTop, numMin)!



回答3:


In Swift 4.2 this can be done using array first(where:) and last(where:) methods. Be aware that the example code below has unsafe dererencing of optional values and will fail if givenValue is outside the range of the values array.

    func findClosest(_ values: [CGFloat], _ givenValue: CGFloat) -> CGFloat {

        let sorted = values.sorted()

        let over = sorted.first(where: { $0 >= givenValue })!
        let under = sorted.last(where: { $0 <= givenValue })!

        let diffOver = over - givenValue
        let diffUnder = givenValue - under

        return (diffOver < diffUnder) ? over : under
    }

    let values:[CGFloat] = [-12.0, 450, 300]

    print(findClosest(values, 64.0))   // -12.0
    print(findClosest(values, 143.0))  // -12.0
    print(findClosest(values, 144.5))  // 300


来源:https://stackoverflow.com/questions/28868277/swift-check-which-value-in-nsarray-is-closest-to-another-given-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!