我正在尝试从下面的函数中检索值。
我只是想能够调用函数使用:
steps = getStepCountForDayXDaysAgo(4)
// Function to query Step Count for X days ago
func getStepCountForDayXDaysAgo(_ daysAgo: Int, completion: @escaping (Double?, Error?) -> Void) {
let healthStore = HKHealthStore()
let stepType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let calendar = Calendar.current
let startDate = calendar.date(byAdding: .day, value: -daysAgo, to: calendar.startOfDay(for: Date()))!
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictEndDate)
let query = HKStatisticsQuery(quantityType: stepType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (query, result, error) in
guard let result = result, error == nil else {
completion(nil, error)
return
}
let steps = result.sumQuantity()?.doubleValue(for: .count())
completion(steps, nil)
}
healthStore.execute(query)
}
然而,Xcode一直提示我使用以下代码:
getStepCountForDayXDaysAgo(2) { (stepCount, error) in
if let stepCount = stepCount {
// Use the step count value here
print("Step count: \(stepCount)")
} else {
// Handle the error here
print("Error: \(error?.localizedDescription ?? "Unknown error")")
}}
我真的不想在错误声明上浪费时间。如果有错误,我需要步数或0。
1条答案
按热度按时间x6yk4ghg1#
你不能避免完成处理程序 *,因为你正在处理异步代码,但你可以摆脱错误和可选结果。
首先更改函数的签名,使完成处理程序只期望
Double
作为输入然后更改查询闭包的内容以匹配完成处理程序
然后可以像这样调用该方法
*你也可以使用async/await