DavidK DavidK - 4 months ago 18
Swift Question

Cannot convert value of type error Swift

I'm following a tutorial on making a simple pedometer app, and I'm getting the following error


Cannot convert value of type '(CMPedometerData!, _) -> Void' to
expected argument type 'CMPedometerHandler' (aka
'(Optional, Optional) -> ()')


on these lines of code:

if(CMPedometer.isStepCountingAvailable()){
let fromDate = NSDate(timeIntervalSinceNow: -86400 * 7)
self.pedoMeter.queryPedometerDataFromDate(fromDate, toDate: NSDate()) { (data : CMPedometerData!, error) -> Void in
print(data)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(error == nil){
self.steps.text = "\(data.numberOfSteps)"
}
})
}
self.pedoMeter.startPedometerUpdatesFromDate(midnightOfToday) { (data: CMPedometerData!, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(error == nil){
self.steps.text = "\(data.numberOfSteps)"
}
})
}
}

Answer

The compiler’s telling you that the handler you’re providing is of the wrong type—you have the first parameter as an implicitly-unwrapped optional rather than an optional (it has a ! rather than a ?), and the second parameter has no type at all. In other words, the bits that look like this:

(data : CMPedometerData!, error) -> Void

…should look like this instead:

(data : CMPedometerData?, error: NSError?) -> Void
Comments