Hello Swift Community,
I have following wierd behaviour with async let
Task {
for workout in items {
// Crash on Xcode 16.2 Swift 6.0.3
async let result1 = workout.getStrokeCount()
async let result2 = workout.getHeartRates()
async let result3 = workout.getSwimmingDistance()
let (data1, data2, data3) = await (result1, result2, result3)
// ... consuming given data
}
}
func getStrokeCount() async -> WorkoutStrokeCountData? {
await withCheckedContinuation { continuation in
let healthStore = HKHealthStore()
let strokeType = ...
let predicate = ...
let strokeQuery = HKSampleQuery(sampleType: strokeType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [.init(keyPath: \HKSample.startDate, ascending: true)], resultsHandler: { (query, results, error) in
if let error {
Logger.e("\(error)")
continuation.resume(returning: nil)
}
if let results = results {
...
continuation.resume(returning: WorkoutStrokeCountData(rawData: results))
} else {
continuation.resume(returning: nil)
}
})
healthStore.execute(strokeQuery)
}
}
func getHeartRates() async -> [WorkoutExecutionRecord]? {
await withCheckedContinuation { continuation in
let healthStore = HKHealthStore()
let heartRateType = ...
let predicate = ...
let heartRateQuery = HKSampleQuery(sampleType: heartRateType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [.init(keyPath: \HKSample.startDate, ascending: true)], resultsHandler: { (query, results, error) in
if let error {
Logger.e("\(error)")
continuation.resume(returning: nil)
}
if let results = results {
...
continuation.resume(returning: items)
} else {
continuation.resume(returning: nil)
}
})
healthStore.execute(heartRateQuery)
}
}
Once I change it to
Task {
for workout in items {
let data1 = await workout.getStrokeCount()
let data2 = await workout.getHeartRates()
let data3 = await workout.getSwimmingDistance()
// ... consuming given data
}
}
It works.
What's the issue with async let
?