Amending property value in array

I have a number of values that can change, and would like to know the closest of them to the number ten (Double), which I do by sorting an array of properties.

I realise that as they're Doubles the array cares about the data type than the property, which is my problem as I would like to locate the one closest (but not including) ten, and then amend it back to ten e.g. if value2 is eight, and this is the closest of all the values, or at least the first in the array to meet that condition if there are multiple, then to amend that to ten:

var value1: Double = 10
var value2: Double = 10
var value3: Double = 10
var value4: Double = 10

let allValues = [value1, value2, value3, value4, value5]

                for value in allValues {
                    if value < 10 {
                        var organisedValues = allValues.sorted() { $0 > $1 }
                        organisedValues[1] = 10  //first result will always be 10, so avoid
                    }
                }

Likely the code above is not the way to achieve this, but what is please ?

I don't understand what you are trying to achieve with your code but you can find the closest value to a target value using something like :

extension Array where Element == Double {
    
    func closest(to target: Double) -> Double? {
        self.reduce(nil) { closest, next in
            guard next != target else { return closest }
            guard let closest = closest else { return next }
        
            func diff(_ el: Double) -> Double {
                Swift.min(Swift.abs(el-target), Swift.abs(el+target))
            }
    
            return diff(closest) < diff(next) ? closest : next
        }
    }
}

[1, 2, 8, 10, 20].closest(to: 10) gives 8
[10, 10, 10].closest(to: 10) gives nil
[].closest(to: 10) gives nil

1 Like

It's an odd request I know, but it did the trick.

I never think to make an extension and usually just use a stand alone function.

I appreciate the built in safety measures and the simplicity of a ternary operator.

Much appreciated.

P.S. my code will be open, so I have mentioned you as a contributor