简体   繁体   中英

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 ?

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.

You may try this...

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

Happy Coding!!!

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM