0
    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.

JKU
  • 123
  • 1
  • 8
  • This is because you have 3 different possible results: true, false or nil – Leo Dabus Sep 30 '17 at 16:08
  • 1
    Possible duplicate of [What does an exclamation mark mean in the Swift language?](https://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language) – mfaani Sep 30 '17 at 16:09

2 Answers2

2

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 { ... }
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • For better readability don't use nil coalescing operator with optional chaining `Bool?` types just use `== true` or `== false` or `== nil`. – Leo Dabus Sep 30 '17 at 16:10
  • Actually, I prefer remove the optional as soon as possible instead of propagating optionals further in the expression: `(self.account.text ?? "").isEmpty`. – Sulthan Sep 30 '17 at 16:15
  • then, which circumstances does the .isEmpty become nil? – JKU Sep 30 '17 at 16:24
  • @JKU The value of `isEmpty` is never `nil`. But the value of the expression `self.account.text?.isEmpty` is `nil` when `text` is `nil`, i.e. the evaluation of `isEmpty` is skipped in that case. – Emil Laine Sep 30 '17 at 16:32
  • @Sulthan Don't use nil coalescence to provide a default value, only to depend on some property of that default value. (e.g. you're relying on `?? ""` to make `isEmpty` be `true` when `text` is `nil`). Instead, just use map: `self.account.text.map{ $0.isEmpty }` – Alexander Sep 30 '17 at 17:08
0
self.account.text

is optional boolean value so it will be nil or boolean. unwrapping the boolean must check it is equal to true or false like in this way.otherwise it will crash because of nil value.

import UIKit
var isempty: Bool?

if isempty == true
{
   print("i am empty")
}
else
{
   print("hy i am not empty")
}
//it will print "Hy i am not empty" because isempty has nil 
Muhammad Shauket
  • 2,643
  • 19
  • 40