Swift – Get Items (Files/Directories) in Directory
To get items in a directory in Swift, use contentsOfDirectory()
function and pass the path of directory for atPath
parameter.
The following code snippet shows how to call contentsOfDirectory() function.
FileManager.default.contentsOfDirectory(atPath: path)
where path
is a String representing the directory location.
contentsOfDirectory() function returns a String array with all the items in the directory as items in String array.
Example
In the following Swift program, we will get the items present in the directory /Users/tutorialkart
.
main.swift
import Foundation let path = "/Users/tutorialkart" do { let itemsInDirectory = try FileManager.default.contentsOfDirectory(atPath: path) print(itemsInDirectory) } catch { print(error) }
Here, contentsOfDirectory() function can throw an Error. So, we marked the function call with try.
Output
["Music", ".DS_Store", ".CFUserTextEncoding", "Pictures", "Desktop", "Library", "Public", "Movies", "Applications", ".Trash", "Documents", "Downloads"]
ADVERTISEMENT
Conclusion
In this Swift Tutorial, we learned how to get the items in a specified directory.