You can get url resource key isRegularFileKey to check if the enumerated url is a regular file. You can also set the options to skip hidden files and package descendants, otherwise it will also copy hidden files like .DS_Store:
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
var files: [URL] = []
FileManager.default.enumerator(at: documentsDirectory, includingPropertiesForKeys: [], options: [.skipsHiddenFiles, .skipsPackageDescendants])?.forEach {
if let url = $0 as? URL, (try? url.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true {
files.append(url)
}
}
You can also get all objects returned from the enumerator and conditionally cast them into an array of URLs and then filter the URLs which meets the condition:
if let files = (FileManager.default.enumerator(at: documentsDirectory, includingPropertiesForKeys: [], options: [.skipsHiddenFiles, .skipsPackageDescendants])?.allObjects as? [URL])?
.filter({
(try? $0.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true
}) {
print(files.count)
}