Swift Core Motion closing problem


I'm trying to convert an old game application built in obj-c to the new swift code. i'm having some issues understanding swift closures and how to use them for example in the"startAccelerometerUpdatesToQueue" method.

i have initialized the motion manager in this way

motionManager!.accelerometerUpdateInterval = (1/40)

then in the viewdidload of my view controller

var queue:NSOperationQueue
motionManager?.startAccelerometerUpdatesToQueue(queue, withHandler: {(accelerometerData :     CMAccelerometerData, error : NSError) in


the "startAccelerometerUpdatesToQueue" is giving me an error and i'm pretty sure i didn't understand the correct closure syntax.

Any ideas?

Actually, you just got the signature wrong – the arguments to your closure need to be optionals (since they are passed from Objective-C, they could be nil). Because of that, the arguments you provide don't match an existing method signature, and because of that you get an error.

Take a look at the iOS 8 API docs, they also provide Swift signatures:

func startAccelerometerUpdatesToQueue(_ queue: NSOperationQueue!,
                          withHandler handler: CMAccelerometerHandler!)

and CMAccelerometerHandler is defined as

typealias CMAccelerometerHandler = (CMAccelerometerData!, NSError!) -> Void

Thus, your call should be:

motionManager?.startAccelerometerUpdatesToQueue(queue, withHandler: {(accelerometerData :     CMAccelerometerData!, error : NSError!) in


And as with any function/method that takes a closure as it's last argument, you can leave it out of the argument list and write it after the call (trailing closure syntax – this example also leaves out the types, as they can be inferred, but that is optional):

motionManager?.startAccelerometerUpdatesToQueue(queue) { accelerometerData, error in