Storing filenames in Swift array

I am looking for code that will allow me to scan a folder in my project and store all filenames with a .jpg extension in an array. This is the code I have to check in the main folder of my xcode project, but how can I store the filenames found inside, inside an array?

let filemanager:NSFileManager = NSFileManager()
let files = filemanager.enumeratorAtPath(NSHomeDirectory())
while let file = files?.nextObject() {
    // store all file names with extension (jpg) in array



source to share

2 answers

Here's an example of how it works. This function returns an array of all file urls in a directory and all its subdirectories from a given path.

func files(atPath: String) -> [NSURL] {
    var urls : [NSURL] = []
    let dirUrl = NSURL(fileURLWithPath: atPath)
    if dirUrl != nil {
        let fileManager = NSFileManager.defaultManager()
        let enumerator:NSDirectoryEnumerator? = fileManager.enumeratorAtURL(dirUrl!, includingPropertiesForKeys: nil, options: nil, errorHandler: nil)
        while let url = enumerator?.nextObject() as! NSURL? {
            if url.lastPathComponent == ".DS_Store" {
    return urls

let allFiles = files("/a/directory/somewhere")




let documentsDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL

let jpgFilesArray = (NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsDirectoryURL, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles | .SkipsSubdirectoryDescendants | .SkipsPackageDescendants, error: nil) as! [NSURL]).sorted{$0.lastPathComponent<$1.lastPathComponent}.filter{$0.pathExtension!.lowercaseString == "jpg"}


as a read-only computed property

var jpgFilesArray: [NSURL] {
    return (NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsDirectoryURL, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles | .SkipsSubdirectoryDescendants | .SkipsPackageDescendants, error: nil) as! [NSURL]).sorted{$0.lastPathComponent<$1.lastPathComponent}.filter{$0.pathExtension!.lowercaseString == "jpg"}




All Articles