Reputation: 59
I have a Sprite Kit Game in Swift.
After I updated Xcode and opened my project, I noticed some changes and an error to a pre-coded syntax saying: "Type of expression is ambiguous without more context" which wasn't there before.
I marked the code with error below. Also Xcode says it's something wrong with .DataReadingMappedIfSafe
.
Do you know a way to fix it?
Thank you in advance!
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
}
}
}
Upvotes: 1
Views: 1800
Reputation: 112857
You need to use try
from Swift 2, see the Swift 2 iBook.The Swift 2.0 declaration is: convenience init(contentsOfFile path: String, encoding enc: UInt) throws
, note the throws
in place of the error parameter.
Error Handling
Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.”
You can learn more on Error Handling in Swift from the book: “Using Swift with Cocoa and Objective-C (Swift 2.1).” iBooks. https://itun.es/de/1u3-0.l
But in any case ignoring errors is not a best practice.
Upvotes: 1
Reputation: 11773
Try this:
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
}
}
Upvotes: 4