title: Swift: define a variable then conditionally set it?
body: <p>This is probably a very simple question...</p>
  
  <p>Here I have some Swift code:</p>
  
  <pre><code>var url: NSURL
  if (someValue &gt; 1) {
      var fullUrl = self.baseUrl + "?id=" + (someValue as! String);
      var url = NSURL(string: fullUrl);
  }
  else {
      var url = NSURL(string: self.baseUrl);
  }
  let req = NSURLRequest(URL: url);
  webView.loadRequest(req);
  </code></pre>
  
  <p>As you can see, I need to conditionally initialize the <code>url</code> variable. However, the method I've used in just about every other strong-type language - initialize the variable then assign to it in the if statement - doesn't seem to be the Swiftly way of doing it.</p>
  
  <p>The above code will refuse to compile with the error "variable 'url' used for being initialized" error. (Of course, from this program flow, you can see that <code>url</code> would always be initialized, but Swift apparently takes nothing for granted.) </p>
  
  <p>Not defining the variable outside the <code>if</code> block results in an unknown identifier error - it seems variables defined inside an <code>if</code> block are scoped only within that block. </p>
  
  <p>Short of just defining an empty NSURL object, is there a better way to do this?</p>
  
  <p>Preferably I'd actually like to use <code>let</code> on this because the NSURL object will never change once it's been created - and Swift tends to recommend using <code>let</code> wherever possible. However, how would you use <code>let</code> in this scenario? (I tried it - the same types of errors occur. Swift is unhappy that I don't actually declare the object itself on the same line as the <code>let</code> statement, but using <code>let</code> inside  the <code>if</code> block results in a scope issue.)</p>