2

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)

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Pop Flamingo
  • 3,023
  • 2
  • 26
  • 64

1 Answers1

2

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
  • 22,115
  • 10
  • 72
  • 85