如何统计指定目录中后缀为jpg的文件数量?
统计指定目录下JPG文件数量的实现方法
方法一:在原有遍历逻辑中扩展统计逻辑
你可以在遍历文件的循环里,增加后缀判断逻辑,累加符合条件的文件数量。修改后的代码如下:
let documentDirectoryPath: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let myFilesPath = "\(documentDirectoryPath)/\(index)" let filemanager = FileManager.default let files = filemanager.enumerator(atPath: myFilesPath) var jpgCount = 0 while let file = files?.nextObject() as? String { // 转为小写后判断后缀,兼容JPG、Jpg等大小写变体 if file.lowercased().hasSuffix(".jpg") { jpgCount += 1 } } print("JPG文件总数:\(jpgCount)")
方法二:Swift函数式写法(更简洁)
利用filter和count方法直接完成筛选与统计,代码更紧凑:
let documentDirectoryPath: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let myFilesPath = "\(documentDirectoryPath)/\(index)" let filemanager = FileManager.default if let allFiles = filemanager.enumerator(atPath: myFilesPath)?.allObjects as? [String] { let jpgCount = allFiles.filter { $0.lowercased().hasSuffix(".jpg") }.count print("JPG文件总数:\(jpgCount)") }
额外注意事项
- 若只需严格匹配小写
.jpg,去掉lowercased()即可;如果需要同时兼容.jpeg,可以把判断条件改成$0.lowercased().hasSuffix(".jpg") || $0.lowercased().hasSuffix(".jpeg")。 enumerator(atPath:)会递归遍历所有子目录下的文件,如果只想统计当前目录(不包含子目录),改用contentsOfDirectory(atPath:)方法,示例如下:
do { let currentDirFiles = try filemanager.contentsOfDirectory(atPath: myFilesPath) let jpgCount = currentDirFiles.filter { $0.lowercased().hasSuffix(".jpg") }.count print("当前目录JPG文件数量:\(jpgCount)") } catch { print("读取目录失败:\(error.localizedDescription)") }
内容的提问来源于stack exchange,提问作者user25462420
相关产品推荐
相关产品推荐

