How to check if a string is non-zero?

If I declared a String this way: var date = String()

and I want to check my nil String weather or not, so I'm trying something like:

 if date != nil{ println("It not nil") } 

But I got an error like: Can not invoke '!=' with an argument list of type '(@lvalue String, NilLiteralConvertible)'

after that i try this:

 if let date1 = date{ println("It not nil") } 

But still I get an error like: Bound value in a conditional binding must be of Optional type

So my question is: how can I verify that String not nil if I declare it this way ?

+5
source share
3 answers

The string cannot be null. This is the point of this type of input to Swift.

If you want it to be possibly zero, declare it as optional:

 var date : String? 

If you want to check that the line is empty (do not do this, it was like the options were created to work):

 if date.isEmpty 

But you really should use the options.

+25
source

You can try this ...

 var date : String! ... if let dateExists = date { // Use the existing value from dateExists inside here. } 

Happy coding !!!

+5
source

In your example, the string cannot be null. To declare a string that can accept nil, you must declare an optional string:

 var date: String? = String() 

After this declaration, your tests will be accurate, and you can assign nil to this variable.

+2
source

Source: https://habr.com/ru/post/1209082/


All Articles