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

Dharmesh Kheni

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?

jrturton

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to check Multiple string is not nil and not empty in swift 5?

How to Nil a object in Swift

UIImage on swift can't check for nil

How to check for `nil` in while loop condition in Swift?

How to check object is nil or not in swift?

How to check for nil with nested convenience failable initializers in Swift?

How to check if NSDictionary is not nil in Swift 2

check if any property in an object is nil - Swift 3

How to check if `Any(not Any?)` is nil or not in swift

How to check if a class model created using alamofire is nil in swift?

Swift - How to check a string not included punctuations and numbers

Swift: How to check for partial occurrence of keywords in a string

Check if string contains optional string in Swift, but only if it's not nil

How to check for nil and compare if != nil on Hashes?

How to check if CGVector is nil?

How to check if imageView is not nil in swift?

Swift check NSDate is not nil

Swift: How to check if an AnyObject is nil or not?

Check JSON Response nil in swift

How to check if a String is an Int in Swift?

How to check nil string in if condition swift

Swift optionals nil check

check for nil and extract data from dictionary in swift

How to check nil for variables in swift and avoid app crashing?

How to check if a string is a date in Swift 5?

How to check String value for nil before converting it to Double

Swift control flow: Unwrapping nil despite if check?

How to check for &{<nil> } in golang

Is there an inline nil check for optional string values in swift while unwrapping?