rename a directory in swift

To rename a directory in Swift, you can use the built-in FileManager class. Simply call the moveItem(at:to:) method, providing the current directory URL and the new directory URL. Here's an example code snippet:

main.swift
let fileManager = FileManager.default
let currentDirectoryURL = URL(fileURLWithPath: "/Users/MyUser/Documents/CurrentDirectoryName")
let newDirectoryURL = URL(fileURLWithPath: "/Users/MyUser/Documents/NewDirectoryName")

do {
    try fileManager.moveItem(at: currentDirectoryURL, to: newDirectoryURL)
    print("Directory renamed successfully")
} catch {
    print("Error renaming directory: \(error.localizedDescription)")
}
426 chars
11 lines

In this example, we first create a FileManager instance. We then create two URLs: one for the current directory we want to rename, and one for the new directory name we want to give it.

We then use a do-catch block to call the moveItem(at:to:) method of the FileManager instance, passing in the current and new directory URLs. If the operation is successful, we print a success message; otherwise, we print an error message with the localized description of the error.

gistlibby LogSnag