How to check object is nil or not in swift?

后端 未结 11 1943
借酒劲吻你
借酒劲吻你 2020-12-30 18:33

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         


        
相关标签:
11条回答
  • 2020-12-30 19:23

    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")
    }
    
    0 讨论(0)
  • 2020-12-30 19:26

    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 讨论(0)
  • 2020-12-30 19:28

    Swift short expression:

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

    or:

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

    or both:

    abc != nil ? doWork(abc) : abc = "string"
    
    0 讨论(0)
  • 2020-12-30 19:30

    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 讨论(0)
  • 2020-12-30 19:32

    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."
    
    0 讨论(0)
提交回复
热议问题