'MacOS path formatting of the dir

I have the following paths (they are an example), I would like to be able to get the result below.

/Users/nameUser
/Users
/Users/nameUser/Downloads/nameDir
/Users/nameUser/Documents/nameDir
/Users/nameUser/Desktop/nameDir/nameProject

Result:

/Users/nameUser
/Users/
~/Downloads/nameDir
~/Documents/nameDir
~/Desktop/nameDir/nameProject


Solution 1:[1]

The FileManager can provide the home directory path. So you can then check if a path starts with it, and if so, replace it with a tilde.

func pathWithTilde(_ path: String) -> String {
    let homeDir = FileManager.default.homeDirectoryForCurrentUser.path + "/"
    if path.starts(with: homeDir) {
        return "~/" + path[homeDir.endIndex...]
    }
    return path
}

Update

Turns out this already exists as a method of NSString (though it will also convert /Users/nameUser to ~). A little String extension help hide the NSString specifics.

extension String {
    var abbreviatingWithTildeInPath: String {
       (self as NSString).abbreviatingWithTildeInPath
    }
}

print("/Users/nameUser/Downloads/nameDir".abbreviatingWithTildeInPath)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leo Dabus