在Swift2中如何检查路径是否为目录?

19

如果希望实现类似于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

这是否可行,如果是,应该如何执行?


3
https://dev59.com/jmAf5IYBdhLWcg3wZB-u#24696209 - Martin R
我同意,抱歉。我已将此标记为重复。 - perhapsmaybeharry
1个回答

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

5
我们到底要如何在Swift中使用这个解决方案?难道真的没有Swift的方法吗? - R.P. Carson
@R.P.Carson 我已经更新了Swift的新版本的答案。 - Sergey Kalinichenko
3
这里是4年后的我们 :D - Dominik Bucher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接