如何在 Swift 中选择数组中最近的元素?

How do I pick the nearest element in an array in Swift?

我很惊讶我找不到关于此的线程,但我需要检查一系列数组的特定值,如果不存在,请检查该值是否介于最大值和最小值之间,然后选择最接近、最负的值分配给变量。

我试图用下面的函数来完成这个,但是它产生了一个编译器错误:无法调用非函数类型的值 "Float!"

有什么方法可以克服编译器错误,还是我应该尝试其他方法?

func nearestElement(powerD : Float, array : [Float]) -> Float {

    var n = 0
    var nearestElement : Float!

    while array[n] <= powerD {

        n++;
    }

    nearestElement = array[n] // error: Cannot call value of non-function type "Float!"

    return nearestElement;
}

然后我想在检查每个数组时在 arrayContains():

中调用 nearestElement()
func arrayContains(array: [Float], powerD : Float) {

    var nearestElement : Float!

    if array.minElement() < powerD && powerD < array.maxElement() {

        if array.contains(powerD) {

            contactLensSpherePower = vertexedSpherePower

        } else {

            contactLensSpherePower = nearestElement(powerD, array)
        }
    }
}

Is there any way to overcome the compiler error, or should I try a different approach?

首先,值得注意的是,行为在很大程度上取决于您使用的 Swift 版本。

不过一般来说,您的问题是将变量命名为与方法相同:

func nearestElement(powerD : Float, array : [Float]) -> Float {

    var n = 0
    var nearestElement : Float! //<-- this has the same name as the function

    while array[n] <= powerD {
        n++;
    }

    nearestElement = array[n] // error: Cannot call value of non-function type "Float!"

    return nearestElement;
}

此外,在 arrayContains 中,您还需要重命名 var nearestElement : Float!,这样也不会产生歧义。

使用高阶函数的优化解决方案:

 func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
    return (values.reduce(values[0]) { abs([=10=]-inputValue) < abs(-inputValue) ? [=10=] :  })
}

Swift每个版本都在改进以优化性能和效率。对于高阶函数,使用此实现可以更容易地找到值数组中最接近的匹配项。根据需要更改值的类型。