Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that the string is not nil in swift?

Tags:

string

swift

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

and I want to check if it is a nil String or not, so that I try something like:

if date != nil{
    println("It's 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's not nil")
}

But still getting an error like:

Bound value in a conditional binding must be of Optional type

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

like image 229
Dharmesh Kheni Avatar asked Dec 15 '14 11:12

Dharmesh Kheni


4 Answers

The string can't be nil. That's the point of this sort of typing in Swift.

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

var date : String? 

If you want to check a string is empty (don't do this, it's the sort of thing optionals were made to work around) then:

if date.isEmpty

But you really should be using optionals.

like image 186
jrturton Avatar answered Nov 06 '22 16:11

jrturton


You may try this...

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

Happy Coding!!!

like image 26
Suresh Kumar Durairaj Avatar answered Nov 06 '22 16:11

Suresh Kumar Durairaj


In your example the string cannot be nil. To declare a string which can accept nil you have to declare optional string:

var date: String? = String()

After that declaration your tests will be fine and you could assign nil to that variable.

like image 34
Greg Avatar answered Nov 06 '22 15:11

Greg


Its a bit late but might help others. You can create an optional string extension. I did the following to set an optional string to empty if it was nil :

extension Optional where Wrapped == String {

    mutating func setToEmptyIfNil() {
        guard self != nil else {
            self = ""
            return
        }
    }

}
like image 24
Anil Arigela Avatar answered Nov 06 '22 16:11

Anil Arigela