尝试保存游戏数据时出错

Error when trying to save gamedata

我正在尝试保存游戏数据

    if !fileManager.fileExistsAtPath(path) {
        // create an empty file if it doesn't exist
        if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") {
            fileManager.copyItemAtPath(bundle, toPath: path)
        }
    }

但是报错:调用可以抛出,但是没有标记'try',错误没有处理。

该变体应该在 Swift 中工作,但在 Swift2.. 如何修改代码?

你需要使用 Swifts 新的 try catch

if (!fileManager.fileExistsAtPath(path)) {
    // create an empty file if it doesn't exist
    if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") {
        do {
            try fileManager.copyItemAtPath(bundle, toPath: path)
        } catch {
            //Catch Error Here
        }

    }
}

这应该可以解决您的问题,如果不能,请写信给我:-)

错误原因

Call can throw, but it is not marked with 'try'

是因为,方法

public func copyItemAtPath(srcPath: String, toPath dstPath: String) throws

表示您正在使用的方法可以抛出错误(看到 throws 关键字?)因此编译器指示您使用 swift try catch 方法

捕获错误
if !fileManager.fileExistsAtPath(path) {
// create an empty file if it doesn't exist
if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") {
             do  {
                try fileManager.copyItemAtPath(bundle, toPath: path)
             }
             catch {
                //Catch error here
             }
        }
    }