title: Swift good coding practice: If statement with optional type Bool
body: <p>So I've been developing an app in Swift, and today I spent nearly an hour debugging a problem that turned out to be completely unexpected. It all resulted from the code below.</p>
  
  <pre><code>if (hero.isAI) { //isAI is a Bool
  
  }
  </code></pre>
  
  <p>The problem was that this if statement ALWAYS returned true. So I thought that maybe I was setting isAI to true somewhere but in the end I realized that I declared isAI as an optional type as shown below.</p>
  
  <pre><code>var isAI: Bool!
  </code></pre>
  
  <p>when it should have been</p>
  
  <pre><code>var isAI: Bool
  </code></pre>
  
  <p>This resulted in the if-statement not checking if isAI was true, but instead checking if it contained a value.</p>
  
  <p>So to be safe now I make sure to write my if-statments like this </p>
  
  <pre><code>if (hero.isAI == true) { //isAI is a Bool
  
  }
  </code></pre>
  
  <p>So my question is, <strong>what are my options to avoid this problem in the future?</strong> (this problem seems extremely dangerous, especially when working on a team on a large project). 
  Should I always write my if-statment explicitly, should I just avoid the optional type for Bools altogether?</p>
  
  <p>Note that I did not have this problem in Xcode Beta 2. This problem came about when I upgraded to Xcode beta 3. I think because in Beta 2 Apple handled implicitly unwrapped Bool in an if-statement by checking its value rather than checking if it contains a value.</p>
  
  <p>Lastly, below is an example of which if-statements run given an optional Bool to better help people understand the problem.</p>
  
  <pre><code>let myBool: Bool! = false
  
  if (myBool) {
      //Runs
  }
  
  if (myBool!) {
      //Won't Run
  }
  
  if (!myBool) {
      //Runs
  }
  
  if (myBool == true) {
      //Won't Run
  }
  </code></pre>