1

I know that if I want to use the variable text outside of this try block in Swift, I would write this code thusly,

var text = NSString()

do {
    text = try NSString( contentsOfURL: url, encoding: NSUTF8StringEncoding ) }
catch let errOpening as NSError {
// ...
}

From days of yore when storage was meted by bytes, my mantra has been to use constants if at all possible. So in the instance where text will be loaded once and never changed, my gut tells me to make it a constant.

do {
    let text = try NSString( contentsOfURL: url, encoding: NSUTF8StringEncoding ) }
catch let errOpening as NSError {
// ...
}

But then I can't use the loaded text outside of the try block. Is there any way to have text be treated as a constant outside of the try block in this context by Swift? Or is this just the yearning of an old man coding in an old style, and I should use var, forget about it, and move on?

Many thanks in advance!

Dribbler
  • 4,343
  • 10
  • 33
  • 53
  • 1
    Declare it as `let text: NSString` before the try block. You can still assign to it, as long as you only do so once. – Crowman Jan 01 '16 at 18:37

1 Answers1

6

You can do:

let text: String
do {
    text = try String(contentsOfURL: url, encoding: NSUTF8StringEncoding)
}
catch let error as NSError {
    // ...
}

(I’ve used String, the native string type in Swift, rather than NSString.)

Assuming later code makes use of text, the catch block must either assign something to it or return from the enclosing function, as constants must be initialised before being used.

Bear in mind that the method you’re using to retrieve the contents of a URL as a string does so synchronously, so if this code runs on the main thread you will block the UI. Look up the NSURLSession docs for details on asynchronously loading the content of URLs, which will avoid blocking the UI.

jbg
  • 4,903
  • 1
  • 27
  • 30
  • Swift native type is String not NSString – Leo Dabus Jan 01 '16 at 20:34
  • I agree. I was using the code from the question to illustrate declaration syntax, and assumed Dribbler had a reason for using NSString so left it that way. – jbg Jan 01 '16 at 20:39
  • Doesn't look like that's the case just mention that he should always use String unless where it is really necessary – Leo Dabus Jan 01 '16 at 20:45
  • I imagine that it’s for the `contentsOfURL:` initialiser, which doesn't exist on String according to a quick scan of the reference, and is the whole reason for the `try` being necessary. – jbg Jan 01 '16 at 20:47
  • 1
    Thanks, must have missed it checking the docs on my phone. Have edited answer. – jbg Jan 01 '16 at 20:54