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
Swift 2
Swift 3
Home Directory
Additionally you can get the home directory like this (returns a
String
/String?
):In Swift 3 and OS X 10.12 it's also possible to use this (returns a
URL
/URL?
):Edit: In Swift 3.1 this got changed to
FileManager.default.homeDirectoryForCurrentUser
Here is a solution that does not depend on the
NSString
class and works with Swift 4:Test code:
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:Return string:
Return URL:
If OS less than 10.12, replace
with
Swift 4 Extension