In Objective-C, is there a difference between if (object == nil) and if (nil == object)?

I would lean towards

if (object == nil) 

but I noticed in some tutorials using

 if (nil == object) 

Is it just a style, or is there any reasonable justification for using any format?

+4
source share
2 answers

This is usually done to prevent the use of an assignment operator instead of a comparison operator. If you accidentally typed this, for example:

 if (object = nil) 

It can compile, but that’s not what you intended.

Using the second form, you provide a compile-time error if you make a mistake, since nil can not can be used as the left operand in an assignment.

Please note: I am not an objective C programmer, but this question is common to many languages.

+10
source

The if (nil == object) version will protect you better if you accidentally put = instead of ==.

+2
source

Source: https://habr.com/ru/post/1312962/


All Articles