Search code examples
swiftcocoansfilemanager

Iterate through files in a folder and its subfolders using Swift's FileManager


I'm quite new to programming a Swift and I'm trying to iterate through the files in a folder. I took a look at the answer here and tried to translate it to Swift syntax, but didn't succeed.

let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)

for element in enumerator {
    //do something
}

the error I get is:

Type 'NSDirectoryEnumerator' does not conform to protocol 'SequenceType'

My aim is to look at all the subfolders and files contained into the main folder and find all the files with a certain extension to then do something with them.


Solution

  • Use the nextObject() method of enumerator:

    while let element = enumerator?.nextObject() as? String {
        if element.hasSuffix("ext") { // checks the extension
        }
    }