I am getting this error:
/Users/xxxx/Desktop/xxx/xxx/ViewController.swift:43:38: Unexpected non-void return value in void function
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)
}
An example of how this is used:
print(readWeight())
Thanks!
I suppose that what you want to achieve is something like that:
Then you can use
readWeight
method like that:So that
myResult
here is the value you are looking for.This is all caused by the fact that
HKSampleQuery
executes asynchronously, so you have no way of immediately knowing the return value. You have to wait for its result, and then process the result in a closure that was given as your method's argument.Probably you should read more about closures:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
Swift: How to pass in a closure as a function argument
The lines inside the braces at the end of:
are actually part of another closure sent as an argument to
HKSampleQuery
's initializer. Think of them as a separate function which will be executed when you callhealthKitStore.execute(weightQuery)
. As noted in Apple's documentation the signature of that closure is:(HKSampleQuery, [HKSample]?, Error?) -> Void
. This means that you can't return anything from the statements inside that closure.Keeping that in mind, you can modify your method as follows:
and then just call
printWeight()
to get the results.You need to use block. So the function itself will return void. When the
HKSampleQuery
starts, it get executed and waiting for result while yourreadWeight
function keep executing and then end returning void. By this time, yourHKSampleQuery
is still executing. When it is done, it posts result by the completion handler. So if you want to do anything with the resultDouble
, you need to do it in the completion handler. So your function will beTo use the result:
Have to return Double value at the end of function.