0

Below is my function which is not changing the return Value. How do I get the function to return the modified returnVal?

 func RecieveActivitySummary() -> HKActivitySummary {
            var returnVal = HKActivitySummary()
            self.makeQuery() { (summary) in

            returnVal = summary //attempting to alter returnVal
            print(returnVal)    //prints out returnVal object that I want with data (seemingly modified)
        }
            print(returnVal)    //prints out unmodified returnVal
            return returnVal    //then goes on to return an empty returnVal object
        }

Here is my makeQuery() function if it helps address the problem:

func makeQuery(completion: @escaping (_ summary : HKActivitySummary) -> ()) {
        
        let calendar = NSCalendar.current
        let endDate = Date()
        
        
        guard let startDate = calendar.date(byAdding: .day, value: 0, to: endDate) else {
            fatalError("error")
        }
        
        let units: Set<Calendar.Component> = [.day, .month, .year, .era]
        
        var startDatecomps = calendar.dateComponents(units, from: startDate)
        startDatecomps.calendar = calendar
        
        var endDatecomps = calendar.dateComponents(units, from: endDate)
        endDatecomps.calendar = calendar
        
        let summariesWithinRange = HKQuery.predicate(forActivitySummariesBetweenStart: startDatecomps, end: endDatecomps)
        
        
        let query = HKActivitySummaryQuery(predicate: summariesWithinRange) {
            (sample, results, error) -> Void in
            if let results = results {
                var summary = results[0]
                completion(summary)
            }
        }
        healthstore.execute(query)
    }
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 3
    You cannot return directly from an asynchronous function like this. That's why the second code sample you list, for example, uses a "completion handler". – jnpdx Aug 06 '22 at 03:39
  • 2
    Related: https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function – vadian Aug 06 '22 at 04:59

0 Answers0