Reputation: 211
I was surprised I could not find a thread on this, but I need to check a series of arrays for a specific value, and if not present, check if the value falls between the max and min value, and then choose the closest, most negative value to assign to a variable.
I attempted to accomplish this with the function below, but it yields a compiler error: Cannot call value of non-function type "Float!"
Is there any way to overcome the compiler error, or should I try a different approach?
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;
}
I'd like to then call nearestElement() when I check each array, within 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)
}
}
}
Upvotes: 2
Views: 2990
Reputation: 295
Optimised solution using higher order functions:
func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}
Swift is advancing with every version to optimise the performance and efficiency. With higher order functions finding the closest match in an array of values is much easier with this implementation. Change the type of value as per your need.
Upvotes: 4
Reputation: 2749
Is there any way to overcome the compiler error, or should I try a different approach?
First, it's worth noting the behavior is largely dependent upon the version of Swift you're using.
In general though, your issue is with naming a variable the same as a method:
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;
}
Also, in arrayContains
, you'll also want to rename var nearestElement : Float!
so there's no ambiguity there as well.
Upvotes: 4