Dharmesh Kheni
Dharmesh Kheni

Reputation: 71852

How to check that the string is not nil in 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?

Upvotes: 5

Views: 36859

Answers (4)

Anil Arigela
Anil Arigela

Reputation: 446

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
        }
    }

}

Upvotes: 1

jrturton
jrturton

Reputation: 119292

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.

Upvotes: 27

Suresh Kumar Durairaj
Suresh Kumar Durairaj

Reputation: 2126

You may try this...

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

Happy Coding!!!

Upvotes: 6

Greg
Greg

Reputation: 25459

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.

Upvotes: 2

Related Questions