Search code examples
swiftnsurlfoundation

"Bash like" paths to NSURL or Foundation path


In most command line tools, paths to files can be specified using formats like those: ../someFile, ~/anotherFile, /foo/bar. How can I init a valid Swift URL or (Foundation) path from such a path?

EDIT:
Maybe a code example is clearer, say I want to init a String from path and I have a foo file in my user directory, doing this:

try String(contentsOfFile: "~/foo")

Doesn't work (error is file does not exist)


Solution

  • In Swift, you can do :

    let str = "~/Documents"
    // NSString has a function for decoding this, not available to String:
    let str2 = (str as NSString).standardizingPath as String 
    
    // Swift deprecated the String path manipulation functions,
    // but supplies them as part of NSURL:
    let url = URL(fileURLWithPath: str)
    let url2 = url.standardizedFileURL // Expands the URL