如何在 Swift 中用波形符扩展路径字符串?我有一个像这样的字符串"~/Desktop"
我想使用这条路径NSFileManager
方法,这需要将波形符扩展为"/Users/<myuser>/Desktop"
.
(这个问题有明确的问题陈述还不存在,这应该很容易找到。一些类似但不令人满意的问题是无法在 Swift 中创建文件路径 https://stackoverflow.com/questions/25626896/can-not-make-path-to-the-file-in-swift/25627019#25627019, 使用 Swift 读取本地文件的简单方法? https://stackoverflow.com/questions/25846459/simple-way-to-read-local-file-using-swift, Objective-C 中基于波形符的路径 https://stackoverflow.com/questions/1675852/tilde-based-paths-in-objective-c/1675867#1675867)
波形符扩展
Swift 1
"~/Desktop".stringByExpandingTildeInPath
Swift 2
NSString(string: "~/Desktop").stringByExpandingTildeInPath
Swift 3
NSString(string: "~/Desktop").expandingTildeInPath
主目录
此外,您还可以像这样获取主目录(返回String
/String?
):
NSHomeDirectory()
NSHomeDirectoryForUser("<User>")
在 Swift 3 和 OS X 10.12 中也可以使用它(返回一个URL
/URL?
):
FileManager.default().homeDirectoryForCurrentUser
FileManager.default().homeDirectory(forUser: "<User>")
编辑:在 Swift 3.1 中,这已更改为FileManager.default.homeDirectoryForCurrentUser
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)