检查路径是否为Swift2中的目录?
If希望获得与Bash的检查路径是否为Swift2中的目录?,swift,directory,swift2,nsfilemanager,Swift,Directory,Swift2,Nsfilemanager,If希望获得与Bash的-dIf条件类似的功能 我知道如何使用fileExistsAtPath()测试文件是否存在,如果文件存在,则返回bool“true”,如果不存在则返回“false”(假设path是包含文件路径的字符串): 但是,我想检查path中指定的路径是否是一个目录,类似于下面的bashcode: if [ -d "$path" ]; then echo "$path is a directory" elif [ -f "$path" ]; then # this i
-d
If
条件类似的功能
我知道如何使用fileExistsAtPath()
测试文件是否存在,如果文件存在,则返回bool“true”,如果不存在则返回“false”(假设path
是包含文件路径的字符串):
但是,我想检查path
中指定的路径是否是一个目录,类似于下面的bash
code:
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")
}
我同意,抱歉。我已将此标记为副本。我们在Swift中究竟要使用什么样的解决方案。真的没有swift方法吗?@R.P.Carson我更新了新版本swift的答案。四年后的今天:D
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")
}