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?
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With