2015-10-19 99 views
0

我很驚訝我找不到這個線程,但我需要檢查一系列數組的特定值,如果不存在,檢查值是否落在最大值和最小值之間,然後選擇最接近,分配給變量的最負值。如何在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; 
} 

我想,然後調用nearestElement()當我檢查每個數組,arrayContains()內:

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) 
     } 
    } 
} 
+2

您不應該爲函數中的函數和變量選擇相同的名稱。 –

回答

4

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!所以沒有歧義那裏。

+0

對不起,我應該澄清Swift 2.0。 – NoClue

相關問題