1

“…you should almost never need to use the NSString class directly in your own code”

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks. https://itun.es/us/1u3-0.l

Despite this bold statement, I think I have found a situation where I need an NSString. For instance, consider this code block:

NSString(
    contentsOfURL: NSURL(string: "http://api.stackexchange.com/answers?site=stackoverflow"),
    encoding: NSUTF8StringEncoding,
    error: &error)

I can't do that with a Swift string, right? Either way, this doesn't work:

String(
    contentsOfURL: NSURL(string: "http://api.stackexchange.com/answers?site=stackoverflow"),
    encoding: NSUTF8StringEncoding,
    error: &error) //Compiler error

So should I just use NSString here? Or is there another preferred way to do this in Swift?

1
  • 1
    To be fair, you really shouldn't be using NSString +contentsOfURL:..., because it makes a synchronous networking request. Use NSURLSession dataTaskWithURL:completionHandler: instead. Commented Oct 15, 2014 at 22:10

2 Answers 2

1

The difference is that with a String the NSURL cannot be nil, but the return from NSURL(...) is an optional - you need to unwrap it:

var error: NSError? = nil
String(
    contentsOfURL: NSURL(string: "http://api.stackexchange.com/answers?site=stackoverflow")!,
    // NB ! after NSURL(...)
    encoding: NSUTF8StringEncoding,
    error: &error)

Or more explicitly (and correctly) :

var error: NSError? = nil
if let url = NSURL(string: "http://api.stackexchange.com/answers?site=stackoverflow") {
    String(
        contentsOfURL: url,
        encoding: NSUTF8StringEncoding,
        error: &error)
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried pasting both of those into a Playground, but both times I got compiler errors.
This answer is correct for Xcode 6.1, but not Xcode 6.0
0

The Foundation framework extends the Swift-native String type to have the same initializers as NSString, so the documentation is correct. (Thanks, newacct.)

var error: NSError?
let urlString: String? = String(
    contentsOfURL: NSURL(string: "http://api.stackexchange.com/answers?site=stackoverflow")!,
    encoding: NSUTF8StringEncoding,
    error: &error)

Just make sure to watch your optionals - that initializer for NSURL returns an optional that needs to be unwrapped to use in the NSString initializer, which itself returns an optional. The compiler may have been complaining about that in typically obtuse fashion.

1 Comment

If Foundation is imported, String does have initializers for contentsOf... and format:arguments: in Xcode 6.1.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.