Finding the x value of the max y value in an array

I have an array of DataPoints, with an x and y value:

struct DataPoint: Identifiable, Hashable {
    let x: Double
    let y: Double
    
    var id: String { String(x/y) }
}

I am trying to get the x value that corresponds to the max y value. I am using this, but sometimes get an out of range error:

let dataPoints: [DataPoint] = await calculateDataPoints() 

if let index = dataPoints.indices.max(by: { dataPoints[$0].y < dataPoints[$1].y }) {
    return dataPoints[index].x
}

calculateDataPoints() is an async function.

Maybe there is another way to do this?

>Solution :

I think you should first check if the dataPoints array is empty before finding the maximum value, in my scenario if the dataPoints array is empty, the max(by:) function will return nil,so the code inside the if let block will not be executed.

If you want to return a default value of 0.0 when the dataPoints array is empty:

let dataPoints: [DataPoint] = await calculateDataPoints()

if let maxDataPoint = dataPoints.max(by: { $0.y < $1.y }) {
    return maxDataPoint.x
} else {
    return 0.0
}

Leave a Reply