Swift: How to expand a tilde in a path String

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".

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


Tilde expansion
Swift 1
"~/Desktop".stringByExpandingTildeInPath
Swift 2
NSString(string: "~/Desktop").stringByExpandingTildeInPath
Swift 3
NSString(string: "~/Desktop").expandingTildeInPath
Home Directory

Additionally you can get the home directory like this (returns a String/String?):

NSHomeDirectory()
NSHomeDirectoryForUser("<User>")

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

Edit: In Swift 3.1 this got changed to FileManager.default.homeDirectoryForCurrentUser

expandingTildeInPath, A new string made by removing extraneous path components from the receiver. SDKs. iOS 2.0+; macOS 10.0+; Mac Catalyst 13.0+; tvOS 9.0+; watchOS 2.0+. Framework Expanding an initial tilde expression using expandingTildeInPath . The path extension, if any, of the string as interpreted as a path. string By Abbreviating With Tilde In Path A new string that replaces the current home directory portion of the current path with a tilde (~) character. -   string By Appending Path Component:


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

standardizingPath, 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  A new string made by expanding the initial component of the receiver, if it begins with “ ~ ” or “ ~user ”, to its full path value. Returns a new string matching the receiver if the receiver’s initial component can’t be expanded. Note that this method only works with file paths (not, for example, string representations of URLs).


Swift 4 Extension

public extension String {

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

}

swift: Swift: How to expand a tilde in a path String, 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  A new string that replaces the current home directory portion of the current path with a tilde (~) character. - string By Appending Path Extension: Returns a new string made by appending to the receiver an extension separator followed by a given extension.


Here is a solution that does not depend on the NSString class and works with 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
}

Test code:

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

The reason for splitting the code into two methods is that nowadays you rather want URLs when working with files and folders and not string paths (all new APIs use URLs for paths).

By the way, if you just want to know the absolute path of ~/Desktop or ~/Documents and similar folders, there's an even easier way for that:

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 Recipes: A Problem-Solution Approach, Don't forget that if you use the tilde (~) to start your path, you must expand the path Copy the contents of Listing 7-7 into the main.swift file, replacing its contents. You should change the path string "~/Documents/Fonts" to reference a similar  There's two mechanisms in Unix concering the tilde in paths: expand ~ at the beginning of a path string to the current user's home directory. expand ~user at the beginning of a path string to the given user's home directory. The first part should be quite trivial to add if #682 get implemented.


Tilde Expansion (Bash Reference Manual), If this login name is the null string, the tilde is replaced with the value of the HOME shell variable. If HOME is unset, the home directory of the user executing the  A new string based on the current string object. If the new string specifies a file in the current home directory, the home directory portion of the path is replaced with a tilde (~) character. If the string does not specify a file in the current home directory, this method returns a new string object whose path is unchanged from the path in the current string. Note that this method only works with file paths. It does not work for string representations of URLs.


FileManager, File URLs are URLs with a file:// scheme in addition to a file path. FileManager has methods that accept both paths and URLs — often Swift Objective-C. let fileURL: URL = /path/to/file let fileExists = FileManager.default. String Representations of File Paths. NSString provides a rich set of methods for manipulating strings as file-system paths. You can extract a path’s directory, filename, and extension, expand a tilde expression (such as “~me”) or create one for the user’s home directory, and clean up paths containing symbolic links, redundant slashes, and references to “.” (current directory) and


code.swift · GitHub, if !path.isEqual(to:"") { // "if the string has contents, then expand the path". path = path.expandingTildeInPath as NSString // cast `as NSString` is  Returns a new string that expands a tilde in this string (indicating the user's home dir) into a full path.