How to check object is nil or not in swift?

Swift

Swift Problem Overview


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?

Swift Solutions


Solution 1 - Swift

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.

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

Solution 3 - Swift

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

Solution 4 - Swift

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

Solution 5 - Swift

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

Solution 6 - Swift

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.

Solution 7 - Swift

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
 }

Solution 8 - Swift

Swift 4.2

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

    return false
}

Usage

if isValid(selectedPost)
{
    savePost()
}

Solution 9 - Swift

Swift short expression:

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

or:

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

or both:

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

Solution 10 - Swift

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

Solution 11 - Swift

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDharmesh KheniView Question on Stackoverflow
Solution 1 - SwiftsapiView Answer on Stackoverflow
Solution 2 - SwiftAniket BochareView Answer on Stackoverflow
Solution 3 - SwiftVijay BhushanView Answer on Stackoverflow
Solution 4 - SwiftAditya DeshmaneView Answer on Stackoverflow
Solution 5 - SwiftAdrian SluytersView Answer on Stackoverflow
Solution 6 - SwiftHemanshu LiyaView Answer on Stackoverflow
Solution 7 - SwiftEggheadView Answer on Stackoverflow
Solution 8 - SwiftUdit KhandelwalView Answer on Stackoverflow
Solution 9 - SwiftEvsenevView Answer on Stackoverflow
Solution 10 - SwiftShakeel AhmedView Answer on Stackoverflow
Solution 11 - SwiftsnehaView Answer on Stackoverflow