How to check object is nil or not in swift?
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."
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.