13

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

(这个带有明确问题陈述的问题还不存在,这应该很容易找到。一些类似但不令人满意的问题是Can not make path to the file in SwiftSimple way to read local file using Swift?基于波浪号Objective-C 中的路径

4

4 回答 4

33

波浪号扩展

斯威夫特 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?):

FileManager.default().homeDirectoryForCurrentUser
FileManager.default().homeDirectory(forUser: "<User>")

编辑:在 Swift 3.1 中,这已更改为FileManager.default.homeDirectoryForCurrentUser

于 2016-07-03T18:23:58.590 回答
3

返回字符串:

func expandingTildeInPath(_ path: String) -> String {
    return path.replacingOccurrences(of: "~", with: FileManager.default.homeDirectoryForCurrentUser.path)
}

返回网址:

func expandingTildeInPath(_ path: String) -> URL {
    return URL(fileURLWithPath: path.replacingOccurrences(of: "~", with: FileManager.default.homeDirectoryForCurrentUser.path))
}

如果操作系统低于 10.12,请更换

FileManager.default.homeDirectoryForCurrentUser

URL(fileURLWithPath: NSHomeDirectory()
于 2018-07-05T12:10:14.547 回答
1

这是一个不依赖于NSString类并适用于 Swift 4 的解决方案:

func absURL ( _ path: String ) -> URL {
    guard path != "~" else {
        return FileManager.default.homeDirectoryForCurrentUser
    }
    guard path.hasPrefix("~/") else { return URL(fileURLWithPath: path)  }

    var relativePath = path
    relativePath.removeFirst(2)
    return URL(fileURLWithPath: relativePath,
        relativeTo: FileManager.default.homeDirectoryForCurrentUser
    )
}

func absPath ( _ path: String ) -> String {
    return absURL(path).path
}

测试代码:

print("Path: \(absPath("~"))")
print("Path: \(absPath("/tmp/text.txt"))")
print("Path: \(absPath("~/Documents/text.txt"))")

将代码分成两种方法的原因是,现在您在处理文件和文件夹时更希望使用 URL,而不是字符串路径(所有新 API 都使用 URL 作为路径)。

顺便说一句,如果您只想知道~/Desktop~/Documents类似文件夹的绝对路径,还有一种更简单的方法:

let desktop = FileManager.default.urls(
    for: .desktopDirectory, in: .userDomainMask
)[0]
print("Desktop: \(desktop.path)")

let documents = FileManager.default.urls(
    for: .documentDirectory, in: .userDomainMask
)[0]
print("Documents: \(documents.path)")
于 2018-04-07T00:35:23.800 回答
1

Swift 4 扩展

public extension String {

    public var expandingTildeInPath: String {
        return NSString(string: self).expandingTildeInPath
    }

}
于 2018-12-03T15:41:48.023 回答