Swift snippet #6 β€” Bool??

Ritesh Gupta
Swift Snippets πŸš€
1 min readDec 5, 2016

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 😊

--

--