检查path是否为Swift2中的目录



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

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

if NSFileManager.fileExistsAtPath(path) {
    print("File exists")
} else {
    print("File does not exist")
}

但是,我想检查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

这可能吗?如果可能,应该如何执行?

您可以使用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")
}

最新更新