查看文件删除是否成功

Check if file deletion was successful

根据 XCode 文档(alt-click),removeItemAtPath returns true 或 false。然而,下面的代码给了我以下错误:

无法将类型“()”的值转换为指定类型 'Bool'。

let result: Bool = try NSFileManager.defaultManager().removeItemAtPath(<my file path here>)

文档有错吗?如何检查文件是否成功删除?如果在removeItemAtPath中抛出错误,是否会跳过以下代码的执行?

示例:

try NSFileManager.defaultManager().removeItemAtPath(<my file path here>)
doOtherStuff()

如果抛出错误,是否会调用 doOtherStuff?

根据评论,您想使用 Do/Try/Catch 块。

 do {
        try NSFileManager.defaultManager().removeItemAtPath("<my file path here>")
    } catch {
        print ("The file could not be removed")
    }

如果文件被删除,try块中的代码将被执行。如果没有删除文件,则执行catch块中的代码。

例如,如果您将 print ("Success") 放在 try 块中,则在成功删除文件后将执行该 print 语句。

同样在catch块中,如果文件没有被删除,你可以放任何你想执行的代码。我放了一个简单的打印语句,但你可以放任何你想要的。

这是我与 try/catch 一起使用的方法:

func deleteFileFromDocumentsDirectory(fileName : String) -> () {

    // Optional 1: split file by dot "."
    let fullName = fileName.componentsSeparatedByString(".")
    let fileName = fullName[0];
    let fileExtension = fullName[1];

    let documentsFolder : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask, true)[0]
    let fileManager = NSFileManager.defaultManager()
    let destinationPath = documentsFolder + "/" + fileName + "." + fileExtension
    // Optional 2: check, if file exits
    let fileExists = fileManager.fileExistsAtPath(destinationPath)

    if fileExists {
        do {
            try fileManager.removeItemAtPath(destinationPath)
        } catch let error as NSError {
            print("Could not delete \(error), \(error.userInfo)")
        }
    }
}

Will doOtherStuff be called if an error was thrown?

没有。 try 的全部意义在于,如果它失败,它会立即从当前范围退出。那就是 为什么 你不必捕获和测试结果 and/or 一个 NSError 指针(并且不能这样做)。