If like to attain functionality similar to that of Bash's -d
if
condition.
I am aware of how to test if a file exists with fileExistsAtPath()
, which returns a bool "true" if the file exists and "false" if it doesn't (assuming path
is a string containing the path to the file):
if NSFileManager.fileExistsAtPath(path) {
print("File exists")
} else {
print("File does not exist")
}
However, I would like to check if the path specified in path
is a directory, similar to the following 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
Is this possible, and if yes, how should it be performed?
You can use an overload of fileExistsAtPath
that tells you that path
represents a directory:
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")
}