如何在Swift中使用波浪号扩展路径String?我有一个像"~/Desktop"
这样的字符串,我想将此路径与NSFileManager
方法一起使用,这需要将波浪号扩展为"/Users/<myuser>/Desktop"
。
(这个问题没有明确的问题说明,应该很容易找到。类似但不令人满意的问题是Can not make path to the file in Swift,Simple way to read local file using Swift?和Tilde-based Paths in Objective-C)
最佳答案
波浪号扩展
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
关于Swift:如何在路径字符串中扩展波浪号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38173050/