NSURL 或 Foundation 路径的“类似 Bash”路径

问题描述 投票:0回答:1

在大多数命令行工具中,可以使用以下格式指定文件路径:

../someFile
~/anotherFile
/foo/bar
。如何从这样的路径初始化有效的 Swift
URL
或(Foundation)路径?

编辑:
也许代码示例更清楚,假设我想从路径初始化一个字符串,并且我的用户目录中有一个

foo
文件,这样做:

try String(contentsOfFile: "~/foo")

不起作用(错误是文件不存在)

swift nsurl foundation
1个回答
2
投票

在 Swift 中,你可以这样做:

let str = "~/Documents"
// NSString has a function for decoding this, not available to String:
let str2 = (str as NSString).standardizingPath as String 

// Swift deprecated the String path manipulation functions,
// but supplies them as part of NSURL:
let url = URL(fileURLWithPath: str)
let url2 = url.standardizedFileURL // Expands the URL
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.