开发者

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

开发者 https://www.devze.com 2023-01-03 20:56 出处:网络
I would lean towards if (object == nil) but I\'ve noticed in some tutorials the use of if (nil == object)

I would lean towards

if (object == nil)

but I've noticed in some tutorials the use of

if (nil == object)

Is this just a 开发者_Python百科style thing, or is there some justified rationale for using either format?


This is typically done to prevent using an assignment operator instead of a comparison operator. If you accidently typed this for instance:

if (object = nil)

It may compile but it isn't what you intended.

By using the second form you will ensure a compile time error if you mistype it, as nil cant be used as the left operand in assignments.

Please note I'm not an objective C programmer, but this question is generic to a lot of languages.


The if (nil == object) version protects you better in case you accidentally put = instead of ==.

0

精彩评论

暂无评论...
验证码 换一张
取 消