38

How do you convert an NSURL to a String in Swift?

The following:

var directoryURL: NSURL
var urlString: String = nsurlObject as String

Throws the error:

Cannot convert value of type 'NSURL' to type 'String' in coercion

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
JBaczuk
  • 13,886
  • 10
  • 58
  • 86

1 Answers1

115

It turns out there are properties of NSURL you can access (see Swift Reference):

var directoryURL: NSURL
var urlString: String = directoryURL.absoluteString
// OR
var urlString: String = directoryURL.relativeString
// OR
var urlString: String = directoryURL.relativePath
// OR
var urlString: String = directoryURL.path
// etc.
JBaczuk
  • 13,886
  • 10
  • 58
  • 86