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

1 Answer 1

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.
1
  • 7
    You've missed the one you will probably need most directoryURL.path!
    – Leo Dabus
    Nov 4, 2015 at 1:03

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.