How to Check if a Directory Exists

I was surprised to see that, still in Swift 6, the file management functionality relies on Objective-C. Here is a simple example how to check if a directory exists on the local filesystem.

import Foundation
@main
struct App {
    func run() {
        let directoryPath : String = "/your/directory/path"
        /* Doesn't matter what value this starts as.
        It will get overwritten by the fileExists function */
        var isDir : ObjCBool = false 
        if FileManager.default.fileExists(atPath: directoryPath, isDirectory: &isDir) {
            if isDir {
                // a folder exists at the given path
            }
            else {
                // a file exists at the given path
            }
        }
        else {
            // neither a file nor a directory exist at the given path
        }
    }
}

Let Me Help

Do you have a software project that involves the Swift programming language? Perhaps you wish to write a Swift on Server backend or you want to port Objective-C code into Swift. Whether you are looking for a big or small improvement to your project, I can help. Sign up for Swift programming language consulting by Bill Paetzke at swift@billpaetzke.com. Rates are $85 USD for 30 minutes or $160 USD for one hour. Consultations are provided virtually over video conference (i.e. Zoom).


Swift Programming Language Topics by Bill Paetzke © 2024