You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift遍历macOS目录排除包(如应用)无输出问题求助

问题分析与解决

你的问题核心在于两个enumerator方法返回的元素类型不同:

  • 第一个enumerator(atPath:)返回的枚举元素是相对路径字符串
  • 第二个enumerator(at:includingPropertiesForKeys:options:)返回的枚举元素是URL对象

你在第二个代码里依然尝试把元素转成String,导致类型转换失败,所有元素都被guard语句过滤,自然没有输出。

修正后的代码

func traverseDirectoryTree() {
    let path = "/Users/mica/Downloads/TEST"
    let url = URL(filePath: path) // Swift 5.6+,返回非可选URL,无需加!

    print("try to scan Dir")
    
    if let enumerator = FileManager.default.enumerator(
        at: url,
        includingPropertiesForKeys: [.nameKey, .isDirectoryKey, .fileSizeKey],
        options: [.skipsPackageDescendants]
    ) {
        for case let fileURL as URL in enumerator {
            // 获取文件名
            let fileName = fileURL.lastPathComponent
            print("\(fileName)")
            
            // 获取文件属性(通过URL直接获取)
            do {
                let attributes = try fileURL.resourceValues(forKeys: [.fileSizeKey, .fileResourceTypeKey, .referenceCountKey])
                if let size = attributes.fileSize {
                    print("   Size:\(size)")
                }
                if let type = attributes.fileResourceType {
                    print("   Type:\(type.rawValue)")
                }
                if let refCount = attributes.referenceCount {
                    print("   Reference Count:\(refCount)")
                }
            } catch {
                print("   获取属性失败:\(error.localizedDescription)")
            }
            print("")
        }
    } else {
        print("creating enumerator failed")
    }
}

关键修正点

  1. 元素类型处理:用for case let fileURL as URL遍历枚举器,直接获取URL对象
  2. URL创建:URL(filePath:)返回非可选值,无需强制解包
  3. 属性获取:通过URL.resourceValues(forKeys:)方法获取指定属性,替代原来的enumerator.fileAttributes,更符合该枚举器的使用方式
  4. 选项生效:.skipsPackageDescendants会自动跳过.app、.framework等包目录的内容,达到你想要的效果

内容的提问来源于stack exchange,提问作者mica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 20:50:23