是的,我看到了previous question对此,但我仍然无法让它发挥作用。我以前的 Swift2 代码是...
motionMgr.startDeviceMotionUpdatesToQueue(NSOperationQueue(), withHandler: handleMove)
调用:
func handleMove(motion: CMDeviceMotion?, error: NSError?) {
...
}
这在 Swift3 下发生了变化,现在 startDeviceMotionUpdatesToQueue
使用闭包。我一生都无法弄清楚如何调用我现有的方法。我意识到 NSError
变成了 Error
和其他细微的变化,但是闭包调用的语法让我非常困惑。
最佳答案
这应该适合您,Swift 3 中只有一些重命名。
motionMgr.startDeviceMotionUpdates(to: OperationQueue(), withHandler: handleMove)
func handleMove(motion: CMDeviceMotion?, error: Error?) {
// ...
}
handler
的类型为 CMDeviceMotionHandler
,它被定义为闭包的 typealias
:
typealias CMDeviceMotionHandler = (CMDeviceMotion?, Error?) -> Void
我们只需要提供一个闭包(或一个函数,因为函数就是一个闭包),它接受两个参数(CMDeviceMotion?
和Error?
)并且什么也不返回(Void
)。
或者,您可以提供一个闭包而不是像这样的函数:
motionMgr.startDeviceMotionUpdates(to: OperationQueue(), withHandler: { deviceMotion, error in
// ...
})
或使用新的尾随闭包语法:
motionMgr.startDeviceMotionUpdates(to: OperationQueue()) { deviceMotion, error in
// ...
}
关于swift3 - 在 Swift 3 下使用 startDeviceMotionUpdates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41470575/