[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{

        //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?

This question is related to swift

The answer is


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");
}

Swift short expression:

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

or:

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

or both:

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

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 :)


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)")
        }
    }

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")
}

Swift 4.2

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

    return false
}

Usage

if isValid(selectedPost)
{
    savePost()
}

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`
}

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."

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
 }

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.