I am working on a Core Motion Swift Tutorial found here
However, I get an error:
Value of optional type 'NSOperationQueue?' not unwrapped; did you mean to use '!' or '?'?
When I insert a '!' as suggested, I get another error:
Cannot convert value of type'(CMAccelerometerData!, NSError!) -> Void' to expected argument type 'CMAccelerometerHandler' (aka 'Optional , Optional) -> ()')
This is the code:
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(),
withHandler: { (accelerometerData: CMAccelerometerData!, error: NSError!) -> Void in self.outputAccelerationData(accelerometerData.acceleration)
if (error != nil) {
print("\(error)")
}
})
motionManager.startGyroUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:
{ (gyroData: CMGyroData!, error: NSError!) -> Void in
self.outputRotationData(gyroData.rotationRate)
if (error != nil) {
print("\(error)")
}
})
I am trying to learn Core Motion, and these errors are confusing me.
How can I go about fixing this?
This has nothing to do with Core Motion, it's bad Swift code. I suggest that you learn about Swift optional. here is a good source: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html
Now, about your code: gyroData is an optional, so instead of putting the ! in front of the argument in your closure, use this:
if let gData = gyroData {
...
}
so something like this:
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(),
withHandler: { (accelerometerData, error) -> Void in self.outputAccelerationData(accelerometerData.acceleration)
if let x = accelerometerData {
// now x is your unwrapped accelerometerData
}
})