繁体   English   中英

Swift:如何在路径String中扩展波形符

[英]Swift: How to expand a tilde in a path String

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

(这个带有明确问题陈述的问题尚不存在,这应该很容易找到。一些相似但不令人满意的问题是无法在Swift中创建文件的路径, 使用Swift读取本地文件的简单方法?基于Tilde Objective-C中的路径

Tilde扩张

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

返回字符串:

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))
}

如果OS小于10.12,请更换

FileManager.default.homeDirectoryForCurrentUser

URL(fileURLWithPath: NSHomeDirectory()

这是一个不依赖于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)")

Swift 4扩展

public extension String {

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM