'Swift macOS - find all files of a specific extension

I need to find the names of all files that have the extension .pub in the path ~/.ssh.

So in the end I need to have an array of names.

I solved it like this, I wonder if there is a possibility to write it in a better and more compact way as code.

func arrayFile(path: String, ext: String) -> [String] {
  guard let desktopPath = NSSearchPathForDirectoriesInDomains(.desktopDirectory,.userDomainMask,true).first else { return [] }
  let pathConfig = desktopPath.replacingOccurrences(of: "Desktop", with: path)
  let filemanager: FileManager = FileManager()
  let files = filemanager.enumerator(atPath: pathConfig)
  var array = [String]()
  while let file = files?.nextObject() as? String {
    if file.hasSuffix(ext) {
      let name = file.replacingOccurrences(of: ext, with: "")
       array.append(name)
    }
  }
  return array
}

let array = arrayFile(path: ".ssh/", ext: ".pub")
print(array)

Can you give me some suggestions?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source