检查路径是否是 Swift2 中的目录?
Check if path is a directory in Swift2?
如果想获得类似于 Bash 的 -d
if
条件的功能。
我知道如何使用 fileExistsAtPath()
测试文件是否存在,如果文件存在 returns 布尔值 "true" 如果不存在则 "false" t(假设 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")
}
如果想获得类似于 Bash 的 -d
if
条件的功能。
我知道如何使用 fileExistsAtPath()
测试文件是否存在,如果文件存在 returns 布尔值 "true" 如果不存在则 "false" t(假设 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")
}