문제 설명
게임 데이터를 저장하려고 할 때 오류가 발생했습니다. (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)
}
}
하지만 오류가 발생했습니다: 호출이 발생할 수 있지만 '시도'로 표시되지 않고 오류가 처리되지 않습니다.
해당 변종은 Swift에서 작동해야 하지만 Swift2에서는 작동하지 않습니다. 코드를 수정하는 방법은 무엇입니까?
참조 솔루션
방법 1:
You need to use Swifts new 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
}
}
}
This should solve you problem, if not just write me :‑)
방법 2:
Th reason for the error
Call can throw, but it is not marked with 'try'
is because, the method
public func copyItemAtPath(srcPath: String, toPath dstPath: String) throws
indicates that the method that you are using can throw error(See the throws keyword?) so compiler instructs you to catch the error using swift try catch method
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
}
}
}
(by Yanina、Dennis Weidmann、ipraba)