Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if path is a directory in Swift2? [duplicate]

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?

like image 941
perhapsmaybeharry Avatar asked May 14 '16 10:05

perhapsmaybeharry


1 Answers

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")
}
like image 154
Sergey Kalinichenko Avatar answered Oct 27 '22 23:10

Sergey Kalinichenko