Быстрый синтаксис для вызова экранирующего замыкания / функции ...? - PullRequest
0 голосов
/ 01 февраля 2020

Я хотел бы использовать функцию для определения частоты пульса в состоянии покоя от HealthKit, определенную в этой теме:

Запрос в Healthstore для частоты пульса в состоянии покоя, не возвращающий никаких значений

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’

1 Ответ

1 голос
/ 01 февраля 2020

Попробуйте:

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

...