How to check object is nil or not in swift?

后端 未结 11 2024
借酒劲吻你
借酒劲吻你 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: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."
    

提交回复
热议问题