如果想要获得类似于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")
}