Swift 2 to Swift 3.0 motionManager

淺唱寂寞╮ 提交于 2019-12-04 05:21:30

问题


I am converting an app from swift 2 to swift 3 and I'm trying to use the CMMotionManager, but it gives me this error when I try to call the .startAccelerometerUpdates() function... No clue what's wrong though.

This is how I initialize the manager:

let motionManager = CMMotionManager()

Trying to call the function:

    motionManager.startAccelerometerUpdates(to: OperationQueue.main) { [weak self] (data: CMAccelerometerData?, error: NSError?) in
        self!.outputAccelerationData(data!.acceleration)
    }

Error: Cannot convert value of type '(CMAccelerometerData?, NSError?) -> ()' to expected argument type 'CMAccelerometerHandler' (aka '(Optional, Optional) -> ()')

Thanks!


回答1:


The cryptic error message boils down to this: in Swift 3 NSError is bridged to Error instead. Write your code like this and the problem should go away:

motionManager.startAccelerometerUpdates(to: OperationQueue.main) { [weak self] (data: CMAccelerometerData?, error: Error?) in



回答2:


There are many changes in Swift3. Especially in expressions. Many NS suffix of types are removed such as NSError to Error, NSData to Data. Therefore, change NSError to Error. And if you want to prevent performance issue by multiple instances of CMMotionManager, use SwiftyMotionManager.



来源:https://stackoverflow.com/questions/39373411/swift-2-to-swift-3-0-motionmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!