Skip to content

Latest commit

 

History

History
23 lines (17 loc) · 935 Bytes

File metadata and controls

23 lines (17 loc) · 935 Bytes

1.3.43 Listing files. A folder is a list of files and folders. Write a program that takes the name of a folder as a command-line argument and prints out all of the files contained in that folder, with the contents of each folder recursively listed (indented) under that folder’s name.

func contentsOfFolder(_ folderPath: String, nestingLevel: Int) -> String {
   var contents =

   for path in try! fileManager.contentsOfDirectory(atPath: folderPath) {
       contents += contents.padding(toLength: nestingLevel, withPad: " ", startingAt: 0)
       contents += path + "\n"

       let fullPath = folderPath + "/" + path

       var isDirectory: ObjCBool = false
       let exists = fileManager.fileExists(atPath: fullPath, isDirectory: &isDirectory)

       if isDirectory.boolValue {
           contents += contentsOfFolder(fullPath, nestingLevel: nestingLevel + 1)
       }
   }

   return contents
}