Kametrixom Kametrixom - 3 months ago 16x
Swift Question

Swift: How to expand a tilde in a path String

How can I expand a path String with a tilde in Swift? I have a string like

and I'd like to use this path with the
methods, which requires the tilde to be expanded to

(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

NSString(string: "~/Desktop").stringByExpandingTildeInPath

Swift 3

NSString(string: "~/Desktop").expandingTildeInPath

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?):

FileManager.default().homeDirectory(forUser: "<User>")