Search code examples
iphoneobjective-cnimbus

Objective C - iPhone: using nil in comparision


I see some code in Nimbus look like this:

if (nil == someObject)

but I usually type:

if (someObject == nil)

Are there any differences in these statements?


Solution

  • Technically no. The former, Nimbus, is using what is endearingly called "Yoda Conditions".

    The name of the game being foolproofing here. See, the problem is that this:

    if (someObject = nil) // SETS someObject to nil
    

    is totally valid, only one character away from == nil, and really easy to miss. However, if you attempt to do this:

    if (nil = someObject)
    

    your compiler will freak out, preventing the issue.

    Personally, I hate Yoda Conditionals, as I think they're hard to read. It does mean being extra careful with my code, but hey, I'm the better for it, right? It all comes down to style here, so whatever makes you more comfortable, go for.

    Oh, and if you're using Xcode, this is nearly a moot point. If you check out this question, you'll see that Xcode now warns you if you attempt to do an assignment within an if without extra parens. That is,

    if (someObject = nil) // throws a warning, whereas
    if ((someObject = nil)) // does not
    

    making the issue much harder to miss.