0

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)

Vadim Kotov
  • 7,766
  • 8
  • 46
  • 61
Pop Flamingo
  • 2,741
  • 1
  • 23
  • 59

1 Answers1

1

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
Grimxn
  • 21,552
  • 9
  • 72
  • 83