In this tutorial, you will learn how to check if given path is a directory or not in Swift language using fileExists() method.

Check if given Path is a Directory in Swift

To check if given path is a directory or not, in Swift, follow these steps.

  1. Given a path.
  2. Get the default shared File manager using FileManager.defaut.
  3. Take a boolean variable of type ObjCBool, and initialise it to false, say isDir.
  4. Call fileExists() method of the file manager, and pass the path and boolean variable isDir as arguments.
  5. If the given path is a directory, then the given boolean value isDir is set to true.
  6. Or if the given path is not a directory, then the given boolean value isDir is set to false.
  7. You can use a Swift if-else statement with the boolean value isDir as if-condition.

The syntax to call fileExists() method with path and boolean variable passed as arguments is

</>
Copy
fileExists(atPath: path, isDirectory: &isDir)

Examples

1. Check if given path is a directory

In this example, we take a path "/Users/tutorialkart/", and check if this path is a directory or not.

main.swift

</>
Copy
import Foundation

let path = "/Users/tutorialkart/"

let fileManager = FileManager.default
var isDir: ObjCBool = false
fileManager.fileExists(atPath: path, isDirectory: &isDir)

if isDir.boolValue {
    print("Given path is a DIRECTORY.")
} else {
    print("Given path is NOT a DIRECTORY.")
}

Output

We have taken the path such that the path is a directory. Therefore, isDir variable is set to true, and the if-block is executed.

Swift - Check if path is a directory - Output when given path is a directory

2. Given path is not a directory

In this example, we take a path "/Users/tutorialkart/data.txt", and check if this path is a directory.

main.swift

</>
Copy
import Foundation

let path = "/Users/tutorialkart/data.txt"

let fileManager = FileManager.default
var isDir: ObjCBool = false
fileManager.fileExists(atPath: path, isDirectory: &isDir)

if isDir.boolValue {
    print("Given path is a DIRECTORY.")
} else {
    print("Given path is NOT a DIRECTORY.")
}

Output

The given path is a text file, and is not a directory. Therefore, isDir is set to false, and else-block is executed.

Swift - Check if path is a directory - Output when given path is not a directory

Conclusion

In this Swift Tutorial, we have seen how to check if a given path is a directory or not, using fileExists() method, with examples.