Using Optional Binding and managing scope in Swift
<p>Can we not use optional binding on previously declared variables? It seems such a natural thing to be able to do now that there is <code>if let</code> and <code>guard</code>. I'm thinking something in the lines of:</p>

<pre><code>var jsonData:AnyObject?

if jsonData = try? NSJSONSerialization.JSONObjectWithData(data, options: []) {
    //use jsonData! safely
}
//still be able to use jsonData?
</code></pre>

<p>Or</p>

<pre><code>var jsonData:AnyObject?

guard jsonData = try? NSJSONSerialization.JSONObjectWithData(data, options: []) else {
    print("Could not parse JSON")
}
//still use jsonData?
</code></pre>

<p>Why the scope limitations? Why not keep it open for us to use the variables wherever?</p>

<p>What I am trying to do is avoid two separate statements when assigning/unwrapping an optional (and executing conditional code) which is what seemed to be the original purpose of <code>if let</code> and <code>guard</code> to begin with:</p>

<pre><code>var jsonData: AnyObject?

jsonData = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
if(jsonData != nil) {
    //use jsonData! safely
}
//still use jsonData?
</code></pre>

<p>Is there a cool way to go about this or is the only option to use two statements?</p>

<p><strong>EDIT</strong> </p>

<p>Looking over the code again, I see that my main use of this scenario is when trying to <code>print()</code> messages when assigning/unwrapping certain important optional variables <strong>without major redirections of the flow</strong>. The key statements from my <em>actual</em> code here are: </p>

<pre><code>jsonData = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
if(jsonData == nil) {
    print("Could not parse data")
}
</code></pre>

<p>I was under the impression that <code>if let</code> and <code>guard</code> were made exactly for merging those two statements but I'm getting the feeling that that's not really what they were intended for. I hope I posted a more clearer explanation of my question in <a href="https://codereview.stackexchange.com/questions/127600/can-optional-binding-in-swift-help-here">Code Review</a>.</p>