I have made a function that finds the closest element that is smaller and bigger from a user's input.
To manage this I've used the .last() and .first() methods.
func closestNumbers(_ column: [String], value: Int) {
// Gets the closest element in array to userInput
let userInput = value
let rangeA = column
let left = rangeA.last(where: { $0 <= String(userInput)})! // last element that is less or equal to userInput
let right = rangeA.first(where: { $0 >= String(userInput)})! // first element that is bigger or the same as userInput
print(left, userInput, right)
// prints left <= userInput >= right
}
EXAMPLE: If the userInput would be 450 in an array of [100, 200, .... , 1000].
The print should return (400, 450, 500)
However, it returns 1000, 450, 500.
Even though I feel the logic is correct.
String"1000"is less than"400". Just compare the integersString, you should cast them inIntorDoubleinstead. Edit: As @vadian said its most likely due to this cast