copy a directory in swift

To copy a directory in Swift, the FileManager class can be used. The copyItem(atPath:toPath:) method of this class can be used to copy files or directories.

main.swift
let fileManager = FileManager.default
let currentPath = "/path/to/currentDirectory"
let newPath = "/path/to/newDirectory"

do {
    try fileManager.copyItem(atPath: currentPath, toPath: newPath)
    print("Directory copied successfully")
} catch let error as NSError {
    print("Error: \(error.localizedDescription)")
}
321 chars
11 lines

In the above code, a FileManager instance is created and the source and destination directory paths are specified. The copyItem(atPath:toPath:) method is then called and passed the source and destination directory paths. If any error occurs during the copy operation, it will be thrown by the try block and can be caught in the catch block.

Note: The destination directory must not already exist, otherwise the copy operation will fail.

gistlibby LogSnag