× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Using if statements in Swift?

Antonio Bello
Jul 06, 2015
<p>Optional binding should be used if you actually need the unwrapped value. It is a shortcut for a longer expression, and I think it should be thought in those terms. In fact, in swift 1.2 this optional binding expression:</p> <pre><code>if let unwrapped = optional { println("Use the unwrapped value \(unwrapped)") } </code></pre> <p>is syntactic sugar for code like this (remember that optionals are, under the hood, instances of an <code>Optional&lt;T&gt;</code> enumeration):</p> <pre><code>switch optional { case .Some(let unwrapped): println("Use the unwrapped value \(unwrapped)") case .None: break } </code></pre> <p>Using an optional binding and not assigning the unwrapped value to a variable is like having a box which may contain a TV inside. You don't remove the TV from the box if your purpose is to verify whether the box is empty or not - you just open the box and look inside.</p> <p>So, if you need to execute some code if a variable is not nil, but you don't need nor use the actual value contained in the optional variable, then the not-nil check is, in my opinion, the best way to do it.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31169465/Using%20if%20statements%20in%20Swift?/31169769">Stack Overflow</a>.</p>
comments powered by Disqus