Swift: How to expand a tilde in a path String

前端 未结 4 1085
小蘑菇
小蘑菇 2021-02-20 04:22

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,

4条回答
  •  甜味超标
    2021-02-20 04:32

    Return string:

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

    Return URL:

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

    If OS less than 10.12, replace

    FileManager.default.homeDirectoryForCurrentUser
    

    with

    URL(fileURLWithPath: NSHomeDirectory()
    

提交回复
热议问题