How to check object is nil or not in swift?

后端 未结 11 2038
借酒劲吻你
借酒劲吻你 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:17

    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.

提交回复
热议问题