Swift:如何在路径字符串中扩展波浪号

标签 swift path nsfilemanager home-directory tilde-expansion

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

相关文章:

python - 在 Eclipse 中刷新 PyDev 导入路径

linux - 如何将 PATH 中的一个可执行文件优先于具有相同名称且位于不同 PATH 文件中的另一个可执行文件

ios - 文件目录中的图像路径替换

iphone - 为什么使用 NSFileManager 而不是仅使用 NSData 的 writeToFile :atomically: method when creating a new file?

swift - swift 从文件路径读取数据时如何处理符号链接(symbolic link)

ios - 如何为导航栏制作 CAGradientLayer 动画

ios - Alamofire 模块不使用 Swift 3.0.1 编译

ios - 更改所有 Collection View 单元格中的 View

swift - 如何通过点击“显示更多/显示更少”按钮来更新 TableView Controller 中的约束

javascript - node.js 中的 path.join(__dirname , 'views' ) 和 path.join(__dirname + 'views' ) 之间的区别