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

Swift中FileManager枚举器输出relativePath为完整路径问题(Xcode14.3)

解决Xcode中获取文件相对路径的问题

你遇到的问题出在relativePath的定义和文件枚举器的行为上:

  • URL.relativePath返回的是相对于当前进程工作目录的路径,而非你指定的homeURL,所以会输出完整路径。
  • FileManager的enumerator返回的URL默认是绝对路径,不会保留你最初设置的相对基准。

修改后的代码

let homePath = NSHomeDirectory()
let homeURL = URL(fileURLWithPath: homePath)
guard let fileEnumeratorIncludingSubFolder = FileManager.default.enumerator(
        at: homeURL,
        includingPropertiesForKeys: [],
        options: [.skipsHiddenFiles, .skipsPackageDescendants])
else { fatalError() }

for case let fileURL as URL in fileEnumeratorIncludingSubFolder {
    // 生成相对于homeURL的路径
    if let relativeURL = fileURL.relative(to: homeURL) {
        print(relativeURL.path)
    }
}

关键说明

  • 直接用URL(fileURLWithPath: homePath)创建基准URL更简洁,原代码中用".", relativeTo: homeURL的方式其实等价于直接指向homePath,没有额外作用。
  • fileURL.relative(to: homeURL)会生成一个以homeURL为基准的相对URL,调用它的path属性就能得到你需要的相对路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:54:55