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)
"~/Desktop".stringByExpandingTildeInPath
NSString(string: "~/Desktop").stringByExpandingTildeInPath
NSString(string: "~/Desktop").expandingTildeInPath
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