Swift – How to check object is nil or not in swift


Suppose I have String like :

var abc : NSString = "ABC"

and I want to check that it is nil or not and for that I try :

if abc == nil{



But this is not working and giving me an error. Error Says :

Can not invoke '=='with an argument list of type '(@|value NSString , NilLiteralConvertible)' 

Any solution for this?

Best Answer

If abc is an optional, then the usual way to do this would be to attempt to unwrap it in an if statement:

if let variableName = abc { // If casting, use, eg, if let var = abc as? NSString
    // variableName will be abc, unwrapped
} else {
    // abc is nil

However, to answer your actual question, your problem is that you're typing the variable such that it can never be optional.

Remember that in Swift, nil is a value which can only apply to optionals.

Since you've declared your variable as:

var abc: NSString ...

it is not optional, and cannot be nil.

Try declaring it as:

var abc: NSString? ...

or alternatively letting the compiler infer the type.