如何在Swift中使用波浪号扩展路径String?我有一个像"~/Desktop"这样的字符串,我想将此路径与NSFileManager方法一起使用,这需要将波浪号扩展为"/Users/<myuser>/Desktop"

(这个问题没有明确的问题说明,应该很容易找到。类似但不令人满意的问题是Can not make path to the file in SwiftSimple 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/

10-12 00:19
查看更多