create a directory in swift

To create a directory in Swift, you can make use of the FileManager class. Here's how to do it:

main.swift
let fileManager = FileManager.default
let directoryURL = try! fileManager.url(for: .documentDirectory,
                                        in: .userDomainMask,
                                        appropriateFor: nil,
                                        create: false)
let newDirectory = directoryURL.appendingPathComponent("NewFolder")

if !fileManager.fileExists(atPath: newDirectory.path) {
    do {
        try fileManager.createDirectory(atPath: newDirectory.path,
                                        withIntermediateDirectories: true,
                                        attributes: nil)
        print("Directory created successfully")
    } catch {
        print("Error creating directory: \(error)")
    }
} else {
    print("Directory already exists")
}
782 chars
20 lines

In the example code above, we:

  • Retrieve the documentDirectory URL of the app using the FileManager.
  • Specify the name of the directory that we want to create, which is "NewFolder".
  • Check if the directory already exists. If it does, we print a message indicating that it already exists. If it doesn't, we create it using the FileManager class's createDirectory() method.
  • The withIntermediateDirectories parameter allows intermediate directories to be created if they don't already exist. If set to false and any intermediate directories don't exist, createDirectory() will fail. The attributes parameter allows you to set any additional file attributes when creating the directory. In our example, we pass nil for it.

gistlibby LogSnag