Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check object is nil or not in swift?

Tags:

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{          //TODO:      } 

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?

like image 972
Dharmesh Kheni Avatar asked Nov 01 '14 06:11

Dharmesh Kheni


2 Answers

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.

like image 54
sapi Avatar answered Oct 06 '22 00:10

sapi


The case of if abc == nil is used when you are declaring a var and want to force unwrap and then check for null. Here you know this can be nil and you can check if != nil use the NSString functions from foundation.

In case of String? you are not aware what is wrapped at runtime and hence you have to use if-let and perform the check.

You were doing following but without "!". Hope this clears it.

From apple docs look at this:

let assumedString: String! = "An implicitly unwrapped optional string." 

You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:

if assumedString != nil {     println(assumedString) } // prints "An implicitly unwrapped optional string." 
like image 41
Aniket Bochare Avatar answered Oct 05 '22 23:10

Aniket Bochare