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

Checking the value of an Optional Bool

Antonio Bello
Mar 01, 2015
<p>With optional booleans it's needed to make the check explicit:</p> <pre><code>if boolean == true { ... } </code></pre> <p>Otherwise you can unwrap the optional:</p> <pre><code>if boolean! { ... } </code></pre> <p>But that generates a runtime exception if boolean is <code>nil</code> - to prevent that:</p> <pre><code>if boolean != nil &amp;&amp; boolean! { ... } </code></pre> <p>Before beta 5 it was possible, but it has been changed as reported in the release notes:</p> <blockquote> <p>Optionals no longer implicitly evaluate to true when they have a value and false when they do not, to avoid confusion when working with optional Bool values. Instead, make an explicit check against nil with the == or != operators to find out if an optional contains a value.</p> </blockquote> <p>Addendum: as suggested by @MartinR, a more compact variation to the 3rd option is using the coalescing operator:</p> <pre><code>if boolean ?? false { ... } </code></pre> <p>which means: if boolean is not nil, the expression evaluates to the boolean value (i.e. using the unwrapped boolean value), otherwise the expression evaluates to <code>false</code></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/25523305/Checking%20the%20value%20of%20an%20Optional%20Bool/25523476">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus