本文介绍了将Swift 1.2代码转换为Swift 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我已经尝试了15分钟,试图从Swift 2之前的Xcode 7应用程序中找出如何在Swift 2之前编写的书中使用此代码.这是代码段:

I've tried for 15 minutes trying to figure out how to use this code from a book which was written before Swift 2, in an Xcode 7 app in Swift 2. Here's the code snippit:

    self.coreMotionManager.accelerometerUpdateInterval = 0.3
self.coreMotionManager.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: {

    (data: CMAccelerometerData!, error: NSError!) in

        if let constVar = error { 

 println("There was an error")
         }
         else {

             self.xAxisAcceleration = CGFloat(data!.acceleration.x)
         } })

我收到错误消息:无法使用类型为'(NSOperationQueue,withHandler:(CMAccelerometerData !, NSError!)-> _)-> _'的参数列表调用'startAccelerometerometersUpdatesToQueue'

I get the error: "Cannot invoke 'startAccelerometerUpdatesToQueue' with an argument list of type '(NSOperationQueue, withHandler: (CMAccelerometerData!, NSError!) -> _)'

推荐答案

问题是iOS SDK已针对空性进行了进一步审核,因此从您的代码示例中隐式展开的那些参数是普通的旧可选参数现在(即使用?而不是!):

The issue is that the iOS SDK has been further audited for nullability, so those parameters which are implicitly unwrapped in the code sample from your book, are plain old optionals now (i.e. use ? rather than !):

coreMotionManager.accelerometerUpdateInterval = 0.3
coreMotionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) { (data: CMAccelerometerData?, error: NSError?) -> Void in
    guard data != nil else {
        print("There was an error: \(error)")
        return
    }

    self.xAxisAcceleration = CGFloat(data!.acceleration.x)
}

或更简单地说,让编译器推断闭包参数的类型:

Or, more simply, let the compiler infer the types of the closure parameters:

coreMotionManager.accelerometerUpdateInterval = 0.3
coreMotionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) { data, error in
    guard data != nil else {
        print("There was an error: \(error)")
        return
    }

    self.xAxisAcceleration = CGFloat(data!.acceleration.x)
}

而且,如上所述,由于您使用的是Swift 2,因此您也可能会使用guard语法.

And, as you see above, since you're using Swift 2, you might as well as use the guard syntax, too.

这篇关于将Swift 1.2代码转换为Swift 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:30