Swift snippet #6 β Bool??
Monday, 5th December, 2016
The above snippet simply reverses its boolean value!
Well thereβs a catch!!!
You might be thinking that we already have a negation operator !
in swift then why create a separate var
for it π€. Well thereβs a reason β a negation operator !
only works on a Bool
and not on an optional Bool?
. Consider the following use case:
There are couple of solutions for it like using if-let
or guard
or if you like to live on the edge then may be force-unwrap
π±. In such cases using our new extended var not
could be useful π:
func logic() -> Bool {
let someBool: Bool?
return someBool?.not ?? false
}
If you are wondering about the inception of Swift-Snippets or want to checkout more such snippets then you can find them here π