Q:

Sorting HealthKit data by date

I'm trying to get pulse data from HealthKit and sort them by date for use in a line chart. I'm running a 'for loop' to get the correct dates and put the results in an array before putting the results in the chart but it seems like they get put in a random order and I don't understand why. 
class Pulse {
    var pulse = 0.0
    var startDate = Date()
} 

var pulseData: [Pulse] = []

func getHeartBeatsForAWeek() {

        for i in 1...7 {
            getHeartBeats(startDate: date.getStartOfSpecificDateByAddingToToday(day: -i), endDate: date.getStartOfSpecificDateByAddingToToday(day: -i + 1))
        }
    }

    func getHeartBeats(startDate: Date, endDate: Date) {
        PulseHelper.shared.averageHearthRate(startDate: startDate, endDate: endDate) { (data) in
            DispatchQueue.main.async {
                self.pulseData.append(data)
                self.updateGraph()
            }
        }
    }

Here is my function for fetching the heart rate: 
func averageHearthRate(startDate: Date, endDate: Date, completion: @escaping (Pulse) -> Void) {

        let typeHeart = HKQuantityType.quantityType(forIdentifier: .heartRate)
        let startDate = startDate
        let endDate = endDate
        let predicate: NSPredicate? = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: HKQueryOptions.strictEndDate)

        let query = HKStatisticsQuery(quantityType: typeHeart!, quantitySamplePredicate: predicate, options: .discreteAverage, completionHandler: {(query: HKStatisticsQuery, result: HKStatistics?, error: Error?) -> Void in
            DispatchQueue.main.async(execute: {() -> Void in
                let quantity: HKQuantity? = result?.averageQuantity()
                let beats: Double? = quantity?.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute()))
                print("Got: \(String(format: "%.f", beats!)) from \(startDate)")

                let pulse = Pulse.init()
                pulse.pulse = beats!
                pulse.startDate = startDate
                completion(pulse)
            })
        })
        PermissionsHelper.shared.store.execute(query)
    }

This is what I get when I print the results: 
Got: 82 from 2019-03-30 23:00:00 +0000
Got: 74 from 2019-03-31 22:00:00 +0000
Got: 73 from 2019-03-25 23:00:00 +0000
Got: 74 from 2019-03-27 23:00:00 +0000
Got: 70 from 2019-03-26 23:00:00 +0000
Got: 74 from 2019-03-29 23:00:00 +0000
Got: 108 from 2019-03-28 23:00:00 +0000
I'd like them to get in correct order.

A:

Just after adding an element to your array, you need to use the sort() function.
Here you can find the documentation about all the ways you can implement it.
In this situation, if pulseData is an array of Date ( [Date] ), you just need to call:
   self.pulseData.sort()

EDIT:
As you could see in the link to documentation I posted, there are several ways to use the sort() function in order to apply your sorting rule to a custom object.
In this situation, let's assume you have this class:
      class Pulse {
        var pulse: Double = 0.0
        var startDate = Date()

        init(p: Double,d: Date) {
        self.pulse = p
        self.startDate = d
            }
        }

Create an array of Pulse objects:
        let pulse1 = Pulse(p: .., d: Date(...))
        let pulse2 = Pulse(p: .., d: Date(...))
        var pulseData: [Pulse] = [pulse1, pulse2]

You can sort the array in this way:
        //Ascending order
        pulseData.sort(by: {$0.startDate < $1.startDate})

