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

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


Use the nextObject() method of enumerator:

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


Nowadays (early 2017) it's highly recommended to use the – more versatile – URL related API

let fileManager = FileManager.defaultdo {    let resourceKeys : [URLResourceKey] = [.creationDateKey, .isDirectoryKey]    let documentsURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)    let enumerator = FileManager.default.enumerator(at: documentsURL,                            includingPropertiesForKeys: resourceKeys,                                               options: [.skipsHiddenFiles], errorHandler: { (url, error) -> Bool in                                                        print("directoryEnumerator error at \(url): ", error)                                                        return true    })!    for case let fileURL as URL in enumerator {        let resourceValues = try fileURL.resourceValues(forKeys: Set(resourceKeys))        print(fileURL.path, resourceValues.creationDate!, resourceValues.isDirectory!)    }} catch {    print(error)}


I couldn't get pNre's solution to work at all; the while loop just never received anything. However, I did come across this solution which works for me (in Xcode 6 beta 6, so perhaps things have changed since pNre posted the above answer?):

for url in enumerator!.allObjects {    print("\((url as! NSURL).path!)")}