delete a file in swift

To delete a file in Swift, you can use the FileManager class which has a static default property that returns a shared instance of the file manager. You can then use the removeItem(atPath:) method to delete the file. Here is the code to delete a file:

main.swift
let fileManager = FileManager.default
let filePath = "/path/to/file.txt" // replace with the path to your file
do {
    try fileManager.removeItem(atPath: filePath)
} catch let error as NSError {
    print("Error deleting file: \(error.localizedDescription)")
}
262 chars
8 lines

In this code, we first create an instance of the FileManager class by accessing the default shared instance property. Next, we specify the path to the file we want to delete in the filePath constant. Finally, we call the removeItem(atPath:) method on the file manager instance, passing in the file path as an argument.

It's important to note that the removeItem(atPath:) method can throw an error, so we use a do-catch block to handle any errors that may occur while deleting the file. If an error occurs, we print the localized description of the error to the console.

gistlibby LogSnag