Swift:如何在路径字符串中扩展波浪号 [英] Swift: How to expand a tilde in a path String
问题描述
如何在Swift中使用波浪号扩展路径String?我有一个像"~/Desktop"
这样的字符串,我想将此路径与NSFileManager
方法一起使用,这需要将波浪号扩展为"/Users/<myuser>/Desktop"
.
How can I expand a path String with a tilde in Swift? I have a string like "~/Desktop"
and I'd like to use this path with the NSFileManager
methods, which requires the tilde to be expanded to "/Users/<myuser>/Desktop"
.
(尚不存在带有明确问题说明的问题,应该可以轻松找到.一些类似但不令人满意的问题是使用Swift快速读取本地文件的简单方法?,
(This question with a clear problem statement doesn't exist yet, this should be easily findable. Some similar but not satisfying questions are Can not make path to the file in Swift, Simple way to read local file using Swift?, Tilde-based Paths in Objective-C)
推荐答案
波浪扩展
雨燕1
"~/Desktop".stringByExpandingTildeInPath
雨燕2
NSString(string: "~/Desktop").stringByExpandingTildeInPath
雨燕3
NSString(string: "~/Desktop").expandingTildeInPath
主目录
此外,您还可以像这样获得主目录(返回String
/String?
):
NSHomeDirectory()
NSHomeDirectoryForUser("<User>")
在Swift 3和OS X 10.12中,也可以使用它(返回URL
/URL?
):
In Swift 3 and OS X 10.12 it's also possible to use this (returns a URL
/URL?
):
FileManager.default().homeDirectoryForCurrentUser
FileManager.default().homeDirectory(forUser: "<User>")
在Swift 3.1中,此内容已更改为FileManager.default.homeDirectoryForCurrentUser
In Swift 3.1 this got changed to FileManager.default.homeDirectoryForCurrentUser
这篇关于Swift:如何在路径字符串中扩展波浪号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!