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

前端 未结 4 1165
遇见更好的自我
遇见更好的自我 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:28

    You forgot the 3rd approach, which I use alot:

    if( !data ) {
        return;
    }
    

    Like everyone else has touched on, a lot of it is style... and a lot of it depends on what the compiler supports. Type safe languages like C# and Java make you do:

    if( data == null ) {
        return;
    }
    

    The objective c compiler will allow this type of "syntax sugar" where others will not. My opinion is take advantage of whatever features the compiler offers, and try to make your code as readable as you can for the next guy ;)

提交回复
热议问题