[英]Type of expression is ambiguous without more context
class func unarchiveFromFile(file : NSString) -> SKNode? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks")
var sceneData = NSData.dataWithContentsOfFile(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
So I'm getting a bug at the var sceneData = NSData saying: type of expression is ambiguous with more context. 所以我在var sceneData = NSData处遇到一个错误,说:表达式的类型与更多上下文不明确。 I'm very stuck
我很困
pathForResource
returns an optional. pathForResource
返回一个可选。
dataWithContentsOfFile
expects a non-optional. dataWithContentsOfFile
为非可选。
Unwrap the optional 解开可选
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks")!
or do optional binding 或进行可选的绑定
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") {
// path is safe
}
Actually the correct syntax of dataWithContentsOfFile
is 实际上,
dataWithContentsOfFile
的正确语法是
let sceneData = NSData(contentsOfFile:path, options: .DataReadingMappedIfSafe, error: nil)
and .DataReadingMappedIfSafe
never needs to be unwrapped. 和
.DataReadingMappedIfSafe
不需要解包。
EDIT: 编辑:
The full code: 完整代码:
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") {
// path is safe
let 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
}
return nil
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.