Swift good coding practice: If statement with optional type Bool?
1 Expert Answer
Davis K. answered 11/07/19
Software Engineer (iOS / Swift) with 3+ years of Experience
TLDR: Typically avoid Optionals for vars that have a finite set of potential values like Bool, probably enums
Generally speaking, you should try to avoid using Implicitly Unwrapped Optionals (marked by !) unless you absolutely have to as they can be pretty dangerous if you accidentally consume one that doesn't have a value set. In the example you posted, it seems you already know that myBool is false given that variable is given a value on initialization. Exceptions would include something like Views from Storyboards linked to UIViewControllers where the underlying tool by Apple controls setting those values.
Whether to adopt a pattern usually depends on the design details, but typically I avoid having boolean Optionals since those variables are limited to a binary set (true or false). I'll save Optionals for variables that carry meaning for possibly nil values. For instance take this (slightly trivialized) Person struct example:
It can make sense to use an Optional for middleName because not everyone has a middle name. The nil-ablility carries meaning here.
If we were to extend our type with a var indicating whether a given User is logged in or not:
we would probably not make it an Optional. Why? Well...if you think about it, it is probably safe to assume that a User either logged in or not at any given moment. There is never a practical scenario where we don't know that fact. If you're worried about having an initial value or mutability, you can always specify those:
If you're fetching data from somewhere (like from an API) and worried about waiting for a value to come back from the response body, you can always add an isLoading: Bool somewhere to help you transition between states.
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
C. M.
if(value.isTrue) {} isn't how you write swift. WTF are the parenthesis for?05/13/22