检查路径是否是Swift2中的目录?

per*_*rry 10 directory nsfilemanager swift swift2

如果想要获得类似于Bash -d if条件的功能.

我知道如何测试文件是否存在,如果文件存在fileExistsAtPath()则返回bool"true",如果不存在则返回"false"(假设path是包含文件路径的字符串):

if NSFileManager.fileExistsAtPath(path) {
    print("File exists")
} else {
    print("File does not exist")
}
Run Code Online (Sandbox Code Playgroud)

但是,我想检查指定的路径path是否是目录,类似于以下bash代码:

if [ -d "$path" ]; then
    echo "$path is a directory"
elif [ -f "$path" ]; then
    # this is effectively the same as fileExistsAtPath()
    echo "$path is a file"
fi
Run Code Online (Sandbox Code Playgroud)

这是可能的,如果可以,应该如何执行?

das*_*ght 21

您可以使用一个fileExistsAtPath告诉您path代表目录的重载:

var isDir : ObjCBool = false
let path = ...
let fileManager = FileManager.default
if fileManager.fileExists(atPath: path, isDirectory:&isDir) {
    print(isDir.boolValue ? "Directory exists" : "File exists")
} else {
    print("File does not exist")
}
Run Code Online (Sandbox Code Playgroud)

  • 我们必须在 Swift 中使用的解决方案到底是怎样的。真的没有快捷的方法吗? (4认同)
  • 4年后我们就到了:D (3认同)