Here is a solution that is independent of 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 the code is divided into two methods is because you currently prefer URLs when working with files and folders rather than string paths (all newer APIs use URLs for paths).
By the way, if you just want to know the absolute path of ~/Desktop or ~/Documents and similar folders, it will be even easier for you:
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)")
source share