Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional type 'Bool' cannot be used as a boolean; Test for '!=nil' instead

Tags:

swift

optional

optional type 'Bool' cannot be used as a boolean; Test for '!=nil' instead

enter image description here

I got an error at first if, by replacing the if condition (after), the second if condition did never run. Any idea?

Before:

if(userEmail?.isEmpty || userPassword?.isEmpty || userRepeatPassword?.isEmpty){
      displayMyAlertMessage("All fields are required")
      return
}

if(userPassword != userRepeatPassword){
      displayMyAlertMessage("Passwords do not match.")
}

After:

if(userEmail != nil || userPassword != nil || userRepeatPassword != nil){
      displayMyAlertMessage("All fields are required")
      return
}

if(userPassword != userRepeatPassword){
      displayMyAlertMessage("Passwords do not match.")
}
like image 886
Ghasem Tabatabaei Avatar asked Jun 21 '15 23:06

Ghasem Tabatabaei


People also ask

Can bool be nil?

You can't. A BOOL is either YES or NO . There is no other state.

How do you know if Boolean is optional?

Optionals no longer implicitly evaluate to true when they have a value and false when they do not, to avoid confusion when working with optional Bool values. Instead, make an explicit check against nil with the == or != operators to find out if an optional contains a value.

How do you declare a boolean variable in Swift?

Swift recognizes a value as boolean if it sees true or false . You can implicitly declar a boolean variable let a = false or explicitly declare a boolean variable let i:Bool = true .


1 Answers

you need to wrapped it with ! instead of ?.
That will solved the error message:

if (username!.isEmpty) .....
like image 65
Walter Avatar answered Sep 16 '22 16:09

Walter