Task

Walk a given directory tree and print files matching a given pattern.


Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory.


Note: Please be careful when running any code examples found here.



Related task

   Walk a directory/Non-recursively   (read a single directory). 


import Foundation
 
let fileSystem = FileManager.default
let rootPath = "/"
 
// Enumerate the directory tree (which likely recurses internally)...
 
if let fsTree = fileSystem.enumerator(atPath: rootPath) {
 
    while let fsNodeName = fsTree.nextObject() as? NSString {
 
        let fullPath = "\(rootPath)/\(fsNodeName)"
 
        var isDir: ObjCBool = false
        fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir)
 
        if !isDir.boolValue && fsNodeName.pathExtension == "txt" {
            print(fsNodeName)
        }
    }
}