53

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?

5

12 Answers 12

78

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.

6
  • When I try "if let var = abc as? NSString" then I got an error which says : Downcast from 'NSString?' to 'NSString' only unwraps optionals; did you mean to use "!"? Nov 1, 2014 at 7:15
  • But This "if let variableName = abc" is working thanks for the help.. :) Nov 1, 2014 at 7:16
  • 1
    @DharmeshKheni you can also use: var abc : NSString? = "ABC"
    – User4
    Nov 1, 2014 at 7:18
  • if let syntax for checkin is for optionals. Here in your example you are basically checkin for null which means you should have var abc : String! = "ABC" Nov 1, 2014 at 7:19
  • in swift 2 you can also replace variableName with _
    – dy_
    Nov 12, 2015 at 17:05
10

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."
1
  • Thanks for your explanation. Nov 1, 2014 at 7:31
6

The null check is really done nice with guard keyword in swift. It improves the code readability and the scope of the variables are still available after the nil checks if you want to use them.

func setXYX -> Void{

     guard a != nil  else {
        return;
    }

    guard  b != nil else {
        return;
    }

    print (" a and b is not null");
}
5

I ended up writing utility function for nil check

func isObjectNotNil(object:AnyObject!) -> Bool
{
    if let _:AnyObject = object
    {
        return true
    }

    return false
}

Does the same job & code looks clean!

Usage

var someVar:NSNumber? 

if isObjectNotNil(someVar)
{
   print("Object is NOT nil")
}
else
{
   print("Object is nil")
}
3
  • 2
    +2 since +1 is not allowed :)
    – Marin
    Jan 11, 2017 at 18:46
  • It's returning true even if the object is nil Mar 27, 2018 at 4:50
  • 1
    This is not a good way of testing for nil. If I saw this, in code I was working with, I would know that the author does not understand how Swift optionals should be handled. Use "if let" or "guard" statements as detailed in the other answers. If you don't understand how they work then read the swift documentation or tutorials, particularly with reference to Swift optionals. Aug 15, 2019 at 5:44
1
func isObjectValid(someObject: Any?) -> Any? {
    if someObject is String {
        if let someObject = someObject as? String {
            return someObject
        }else {
            return ""
        }
    }else if someObject is Array<Any> {
        if let someObject = someObject as? Array<Any> {
            return someObject
        }else {
            return []
        }
    }else if someObject is Dictionary<AnyHashable, Any> {
        if let someObject = someObject as? Dictionary<String, Any> {
            return someObject
        }else {
            return [:]
        }
    }else if someObject is Data {
        if let someObject = someObject as? Data {
            return someObject
        }else {
            return Data()
        }
    }else if someObject is NSNumber {
        if let someObject = someObject as? NSNumber{
            return someObject
        }else {
            return NSNumber.init(booleanLiteral: false)
        }
    }else if someObject is UIImage {
        if let someObject = someObject as? UIImage {
            return someObject
        }else {
            return UIImage()
        }
    }
    else {
        return "InValid Object"
    }
}

This function checks any kind of object and return's default value of the kind of object, if object is invalid.

1
  • This will work with Any type, specially when you use Mirror reflection, even if your compare metadata to nil, the above solution doesn't work. Then you have only this solution
    – Sabby
    Jun 20, 2017 at 10:11
1
if (MyUnknownClassOrType is nil) {
    println("No class or object to see here")
}

Apple also recommends that you use this to check for depreciated and removed classes from previous frameworks.

Here's an exact quote from a developer at Apple:

Yes. If the currently running OS doesn’t implement the class then the class method will return nil.

Hope this helps :)

1

Normally, I just want to know if the object is nil or not.

So i use this function that just returns true when the object entered is valid and false when its not.

func isNotNil(someObject: Any?) -> Bool {
        if someObject is String {
            if (someObject as? String) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is Array<Any> {
            if (someObject as? Array<Any>) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is Dictionary<AnyHashable, Any> {
            if (someObject as? Dictionary<String, Any>) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is Data {
            if (someObject as? Data) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is NSNumber {
            if (someObject as? NSNumber) != nil{
                return true
            }else {
                return false
            }
        }else if someObject is UIImage {
            if (someObject as? UIImage) != nil {
                return true
            }else {
                return false
            }
        }
        return false
 }
1
  • how to check if Any is nil sir?
    – kemdo
    Jul 28, 2018 at 16:12
1

Swift 4.2

func isValid(_ object:AnyObject!) -> Bool
{
    if let _:AnyObject = object
    {
        return true
    }

    return false
}

Usage

if isValid(selectedPost)
{
    savePost()
}
0

Swift short expression:

var abc = "string"
abc != nil ? doWork(abc) : ()

or:

abc == nil ? () : abc = "string"

or both:

abc != nil ? doWork(abc) : abc = "string"
0

Swift-5 Very Simple Way

//MARK:- In my case i have an array so i am checking the object in this
    for object in yourArray {
        if object is NSNull {
            print("Hey, it's null!")

        }else if object is String {
            print("Hey, it's String!")

        }else if object is Int {
            print("Hey, it's Int!")

        }else if object is yourChoice {
            print("Hey, it's yourChoice!")

        }
        else {
            print("It's not null, not String, not yourChoice it's \(object)")
        }
    }
0

Swift 4 You cannot compare Any to nil.Because an optional can be nil and hence it always succeeds to true. The only way is to cast it to your desired object and compare it to nil.

if (someone as? String) != nil
{
   //your code`enter code here`
}
0

Swift 5

Crash

Your app crash because parameters receive null, and broke in NSException.

if let parameters = parameters {
    httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
}

Solution

if let parameters = parameters, JSONSerialization.isValidJSONObject(parameters) {
    httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.