如何在Xcode中修复"Type of expression is ambiguous without more context"



我在Swift中有一个Sprite Kit Game。在我更新Xcode并打开我的项目后,我注意到一些变化和预编码语法的错误:"没有更多上下文的表达式类型是模糊的",这在以前是不存在的。我在下面标记了有错误的代码Xcode也说这是.DataReadingMappedIfSafe的问题。你知道怎么修吗?提前感谢!

import UIKit
import SpriteKit
extension SKNode {
  class func unarchiveFromFile(file : String) -> SKNode? {
    if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
      // Error occurs on the following line:
      var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
      var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
      archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
      let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
      archiver.finishDecoding()
      return scene
    } else {
      return nil
    }
  }
}

试试这个:

class func unarchiveFromFile(file : String) -> SKNode? {
    if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
        var sceneData: NSData?
        // Error occurs on the following line:
        do {
            sceneData = try  NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe)
        } catch _ as NSError {
        }
        var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData!)
        archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
        let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
        archiver.finishDecoding()
        return scene
    } else {
        return nil
    }
}

您需要使用Swift 2中的try,请参阅Swift 2 iBook。Swift 2.0的声明是:convenience init(contentsOfFile path: String, encoding enc: UInt) throws,注意throws代替了error参数。

错误处理

错误处理是对程序中的错误条件作出响应并从中恢复的过程。Swift为在运行时抛出、捕获、传播和操作可恢复的错误提供了一流的支持。

你可以从《Using Swift with Cocoa and Objective-C (Swift 2.1)》一书中了解更多Swift中的错误处理。"iBooks。https://itun.es/de/1u3 - 0. - l

但是无论如何忽略错误都不是最佳实践。

相关内容

最新更新