JKU JKU - 3 years ago 166
Swift Question

why (self.account.text?.isEmpty)! is required '!'

if (self.account.text?.isEmpty)! {


}


I just write down this function in ViewDidLoad().
(account is a textfield)

I think that 'self.account.text' can be nil, and 'self.account.text?' is okay.
but I don't know why 'self.account.text?.isEmpty' require '!' - unwrapping.

'self.account.text?.isEmpty' is right, isn't it....?

I always appreciate all answers.

Answer Source

It's because the expression self.account.text?.isEmpty has a value of type bool or the value nil, and you can't use nil as an if-condition.

Using ! here is wrong. If text is nil then the code will crash.

Instead write:

if self.account.text?.isEmpty == true { ... }
// or equivalently:
if self.account.text?.isEmpty ?? false { ... }

if you want to skip the if when text is nil, or:

if self.account.text?.isEmpty != false { ... }
// or equivalently:
if self.account.text?.isEmpty ?? true { ... }

if you want to enter the if when text is nil.

If text should never be nil here then you can just use ! directly after text:

if self.account.text!.isEmpty { ... }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download