J. Mendoza J. Mendoza - 6 months ago 19
Swift Question

Core Motion: Value of optional type 'NSOperationQueue?' not unwrapped

I am following a tutorial from RayWenderLich's website, however, I am stuck on the part about Core Motion.

// CoreMotion
// 1
motionManager.accelerometerUpdateInterval = 0.2
// 2
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {
(accelerometerData: CMAccelerometerData!, error: NSError!) in
// 3
let acceleration = accelerometerData.acceleration
// 4
self.xAcceleration = (CGFloat(acceleration.x) * 0.75) + (self.xAcceleration * 0.25)
})


I try fixing the error, but I end up with more errors.

Any help is appreciated. Thank you.

Answer

The NSOperationQueue's currentQueue returns an optional so you need to unwrap the optional, NSOperationQueue.currentQueue()!.

// CoreMotion
// 1
motionManager.accelerometerUpdateInterval = 0.2
// 2
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: {
    (accelerometerData: CMAccelerometerData?, error: NSError?) in
    // 3
    let acceleration = accelerometerData.acceleration
    // 4
    self.xAcceleration = (CGFloat(acceleration.x) * 0.75) + (self.xAcceleration * 0.25)
})

Also, the closure that you use as handler has wrong parameter types. It's typealias CMAccelerometerHandler = (CMAccelerometerData?, NSError?) -> Void

Comments