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
CodePudding user response:
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 {
func abbreviatingWithTildeInPath() -> String {
return (self as NSString).abbreviatingWithTildeInPath
}
}
print("/Users/nameUser/Downloads/nameDir".abbreviatingWithTildeInPath())