In this tutorial, you will learn how to check if a file exists at given file path in Swift language using fileExists() method.

Check if a File Exists in Swift

To check if a file exists by a given path in Swift, follow these steps.

  1. Given a path to the file.
  2. Get the default shared File manager using FileManager.defaut.
  3. Call fileExists() method on the file manager object, and pass the file path as argument.
  4. If a file exists at given the given path, then fileExists() method returns a boolean value of true.
  5. Or if a file does not exist at given the given path, then fileExists() method returns a boolean value of false.
  6. You can use a Swift if-else statement with the value returned by fileExists() method as condition.

Examples

ADVERTISEMENT

1. Check if file at given path exists [Positive Scenario]

In this example, we take a file path "/Users/tutorialkart/data.txt", and check if a file exists by the given path, using fileExists() method.

We have taken the file path such that the file exists. Therefore, the fileExists() method should return true, and the if-block should execute.

main.swift

import Foundation

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

let fileManager = FileManager.default
if fileManager.fileExists(atPath: path) {
    print("FILE EXISTS.")
} else {
    print("FILE DOES NOT EXIST.")
}

Output

Swift - Check if a File Exists - Positive Scenario output

2. Check if file at given path exists [Negative Scenario]

In this example, we take a file path "/Users/tutorialkart/dummy.txt", and check if a file exists by the given path, using fileExists() method.

We have take the file path such that the file does not exist. Therefore, the fileExists() method should return false, and the else-block should execute.

main.swift

import Foundation

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

let fileManager = FileManager.default
if fileManager.fileExists(atPath: path) {
    print("FILE EXISTS.")
} else {
    print("FILE DOES NOT EXIST.")
}

Output

Swift - Check if a File Exists - Negative Scenario output

Conclusion

In this Swift Tutorial, we have seen how to check if a file exists at given path, using fileExists() method, with examples.