【问题标题】:Swift syntax for calling an escaping closure/function...?用于调用转义闭包/函数的 Swift 语法...?
【发布时间】:2020-01-31 21:28:36
【问题描述】:

我想使用 HealthKit 中的静息心率功能 - 在此线程中定义:

Query to Healthstore for Resting Heart Rate not returning any values

func getuserRestingHeartRate(completion: @escaping (HKQuantitySample) -> Void) {

guard let restingHeartRateSampleType = HKSampleType.quantityType(forIdentifier: .restingHeartRate) else {
    print("Resting Heart Rate Sample Type is no longer available in HealthKit")
    return
}

//1. Use HKQuery to load the most recent samples.
let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast, 
                                                      end: Date(), 
                                                      options: .strictEndDate)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)

//let limit = 1
let sampleQuery = HKSampleQuery(sampleType: restingHeartRateSampleType,
                                            predicate: mostRecentPredicate,
                                            limit: HKObjectQueryNoLimit,
                                            sortDescriptors:
[sortDescriptor]) { (query, samples, error) in
    DispatchQueue.main.async {
        guard let samples = samples,
            let mostRecentSample = samples.first as? HKQuantitySample else {
                print("getUserRestingHeartRate sample is missing")
                return
        }
        completion(mostRecentSample)
    }
}
HKHealthStore().execute(sampleQuery)

}

但我似乎无法在 Swift (5.X) 中找出正确的语法!我猜我的技能水平以上......

试过这个:

var restingHeartRate: HKQuantitySample?

getuserRestingHeartRate(completion: (HKQuantitySample) -> (Void))

上面给出了这个错误: Cannot convert value of type '((HKQuantitySample) -> (Void)).Type' to expected argument type '(HKQuantitySample) -> Void’

getuserRestingHeartRate(completion: (restingHeartRate) -> (Void))

上面给出了这个错误:Expected type before '->’

getuserRestingHeartRate(completion: (restingHeartRate))

上面给出了这个错误:Cannot convert value of type 'HKQuantitySample?' to expected argument type '(HKQuantitySample) -> Void’

【问题讨论】:

  • 请格式化您的代码。使用提供的编辑工具,并阅读提示。
  • 好的 - 进行了编辑!

标签: swift escaping closures


【解决方案1】:

试试这个:

var restingHeartRate: HKQuantitySample?

getuserRestingHeartRate() { (sample) in
  self.restingHeartRate = sample
}

或者,您可以使用:

var restingHeartRate: HKQuantitySample?

getuserRestingHeartRate(completion: { (sample) in
  self.restingHeartRate = sample
})

这是对 Swift 闭包的一个很好的介绍:https://docs.swift.org/swift-book/LanguageGuide/Closures.html

【讨论】:

  • 哇 - 感谢您的快速响应!您的两个建议都非常有效。出于某种原因,我无法理解语法(仍然让我感到困惑 - 但很高兴它有效并且我可以继续!:))
猜你喜欢
  • 2023-03-08
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 2016-11-09
相关资源
最近更新 更多