Asked • 03/18/19

Swift good coding practice: If statement with optional type Bool?

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. if (hero.isAI) { //isAI is a Bool } 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. var isAI: Bool! when it should have been var isAI: Bool This resulted in the if-statement not checking if isAI was true, but instead checking if it contained a value. So to be safe now I make sure to write my if-statments like this if (hero.isAI == true) { //isAI is a Bool } So my question is, **what are my options to avoid this problem in the future?** (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? 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. Lastly, below is an example of which if-statements run given an optional Bool to better help people understand the problem. let myBool: Bool! = false if (myBool) { //Runs } if (myBool!) { //Won't Run } if (!myBool) { //Runs } if (myBool == true) { //Won't Run }

1 Expert Answer


Davis K. answered • 11/07/19

New to Wyzant

Software Engineer (iOS / Swift) with 3+ years of Experience

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.


Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.