Swift Wrapped Functions支持

ie3xauqp  于 2023-04-28  发布在  Swift
关注(0)|答案(1)|浏览(104)

我正在尝试从下面的函数中检索值。
我只是想能够调用函数使用:

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。

x6yk4ghg

x6yk4ghg1#

你不能避免完成处理程序 *,因为你正在处理异步代码,但你可以摆脱错误和可选结果。
首先更改函数的签名,使完成处理程序只期望Double作为输入

func getStepCountForDayXDaysAgo(_ daysAgo: Int, completion: @escaping (Double) -> Void)

然后更改查询闭包的内容以匹配完成处理程序

guard let result = result, error == nil else {
    completion(0)
    return
}

let steps = result.sumQuantity()?.doubleValue(for: .count()) ?? 0
completion(steps)

然后可以像这样调用该方法

var steps = 0.0
getStepCountForDayXDaysAgo(4) { steps = $0 }

*你也可以使用async/await

相关问题