如何在 Swift 中扩展带有波浪号的路径字符串?我有一个类似 "~/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/