Objective-C: Why should one check for != nil

前端 未结 4 1160
遇见更好的自我
遇见更好的自我 2020-12-20 01:31

I often see code like this:

// Approach 1
if(data != nil){
    // Do this and that
}

When one could simply do the check like this:

4条回答
  •  情歌与酒
    2020-12-20 02:22

    Some languages like Java require the conditional within the parenthesis to be a boolean expression. In those languages, you have to spell things like you do in approach 1. If you find yourself jumping from language to language, then I find it easier to stick with that approach. You have one way that works relatively consistently in all languages.

    The second approach is more compact and some find it easier to read. It is just as valid, and probably more commonly used by C/C++/Objective-C developers. If you work exclusively in these C-based languages, it probably is more appropriate for you to use. Even if you choose not to use approach 2 for C-based languages, get used to seeing it whenever you look at other people's code.

提交回复
热议问题