find the contents of a directory in swift

To find the contents of a directory in Swift, you can use the FileManager class. Here's an example code snippet that retrieves the file URLs in a directory:

main.swift
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]

do {
    let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
    print(fileURLs)
} catch {
    print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}
362 chars
10 lines

In the code above, we first retrieve the URL for the directory we want to search (documentsURL in this case). Then, we call contentsOfDirectory(at:includingPropertiesForKeys:) on the file manager object passing in the directory URL and nil for the properties parameter to return all files in the directory.

If there is an error while retrieving the contents of the directory, the code prints out an error message with a description of the encountered error.

related categories

gistlibby LogSnag