macOS 获取文件夹大小

macOS 获取文件夹大小

获取文件夹大小的扩展如下:

swift 复制代码
extension URL {
    var fileSize: Int? { // in bytes
        do {
            let val = try self.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])
            return val.totalFileAllocatedSize ?? val.fileAllocatedSize
        } catch {
            print(error)
            return nil
        }
    }
}
extension FileManager {
    func folderSize(_ dir: URL) -> Int? {
        if let enumerator = self.enumerator(at: dir, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey], options: [], errorHandler: { (_, error) -> Bool in
            print(error)
            return false
        }) {
            var bytes = 0
            for case let url as URL in enumerator {
                bytes += url.fileSize ?? 0
            }
            return bytes
        } else {
            return nil
        }
    }
}

但是返回来的是字节数,如果要转换成 MB 或者 GB,需要自己做转换,那再来扩展吧。

swift 复制代码
extension FileManager {
    func convertBytesToReadableUnit(_ bytes: Int64) -> String {
        let formatter = ByteCountFormatter()
        formatter.countStyle = .binary
        formatter.allowedUnits = [.useAll]
        formatter.includesUnit = true
        formatter.isAdaptive = true
        return formatter.string(fromByteCount: bytes)
    }
}

let bytes: Int64 = 123456789
let readableUnit = FileManager.default.convertBytesToReadableUnit(bytes)
print(readableUnit) // Output: "117.7 MB"
相关推荐
东坡肘子2 天前
Swift 还让你 Excited 吗?-- 肘子的 Swift 周报 #141
人工智能·swiftui·swift
sweet丶4 天前
Swift 元编程-Macro
swift
元Y亨H5 天前
MacBook Air 开发神器:IDEA 与 PyCharm 极简安装及环境配置
macos
yuanyxh6 天前
macOS 应用 - 纯对话生成
前端·macos·ai编程
AI创界者7 天前
PilotTTS 一键整合包(Win/Mac):8G 显存畅跑,实测解锁情绪与副语言的精准控制
人工智能·macos·aigc·音视频
AirDroid_cn8 天前
系统终端与iTerm2字体看起来不一样?macOS Sequoia统一渲染指南
macos
影寂ldy8 天前
WinForm PictureBox控件 + ImageList组件 完整笔记
开发语言·笔记·swift
JiaWen技术圈8 天前
2026 年的 macOS 磁盘清理方法
macos
lichong9518 天前
让AI自己用电脑!Cua:后台操作鼠标键盘,Mac/Windows/Linux全支持
人工智能·macos·ai·计算机外设·agent·提示词