即使设置为Double,Swift也会提供无效返回错误? [英] Swift is giving non-void return error even though it is set to Double?
问题描述
我收到此错误:
/Users/xxxx/Desktop/xxx/xxx/ViewController.swift:43:38: Unexpected non-void return value in void function
即使我的函数设置返回Double。
And others like this even though my functions are set to return Double.
这是每次返回中出现此错误的功能之一。
This is one of the functions of which this error is appearing in every return.
func readWeight() -> Double {
let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)
let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: nil) {
query, results, error in
if (error != nil) {
print(error!)
return 0.0
}
guard let results = results else {
print("No results of query")
return 0.0
}
if (results.count == 0) {
print("Zero samples")
return 0.0
}
guard let bodymass = results[0] as? HKQuantitySample else {
print("Type problem with weight")
return 0.0
}
return bodymass.quantity.doubleValue(for: HKUnit.pound())
}
healthKitStore.execute(weightQuery)
}
例如:
print(readWeight())
谢谢!
推荐答案
您需要使用块。所以函数本身将返回void。当 HKSampleQuery
启动时,它会执行并等待结果,而您的 readWeight
函数保持执行,然后结束返回void。此时,您的 HKSampleQuery
仍在执行。完成后,它会通过完成处理程序发布结果。所以如果你想对结果 Double
做任何事情,你需要在完成处理程序中执行。所以你的功能将是
You need to use block. So the function itself will return void. When the HKSampleQuery
starts, it get executed and waiting for result while your readWeight
function keep executing and then end returning void. By this time, your HKSampleQuery
is still executing. When it is done, it posts result by the completion handler. So if you want to do anything with the result Double
, you need to do it in the completion handler. So your function will be
func readWeight(completion: @escaping (Double) -> Void) {
let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)
let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: nil) {
query, results, error in
if (error != nil) {
print(error!)
completion(0.0)
}
guard let results = results else {
print("No results of query")
completion(0.0)
}
if (results.count == 0) {
print("Zero samples")
completion(0.0)
}
guard let bodymass = results[0] as? HKQuantitySample else {
print("Type problem with weight")
completion(0.0)
}
completion(bodymass.quantity.doubleValue(for: HKUnit.pound()))
}
healthKitStore.execute(weightQuery)
}
要使用结果:
self.readWeight(){ (result) in
//This result is a double value that is returned from HKSampleQuery
}
这篇关于即使设置为Double,Swift也会提供无效返回错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!