0

I used to see conditions like if (something == 0){do it}, but now I've met this sentence in iOS_Book

if (nil == s)

Is this the same as if (s == nil) and if not, what is the difference?

Philip Kendall
  • 4,304
  • 1
  • 23
  • 42
Ilan
  • 401
  • 1
  • 8
  • 21
  • yep they are the same thing – Fonix Jul 28 '13 at 20:54
  • 1
    No, the question I've linked is not just about `NULL`, @PhilipKendall, and the specific constant involved has nothing to do with the answer anyways. "Why `if( 3 == x )`?" has the same answer. – jscs Jul 28 '13 at 20:56
  • I would recommend testing falsey values like: if(!s) or if(!something) – cncool Jul 29 '13 at 02:22

2 Answers2

4

They are the same for testing, but putting the nil to the left will save you from the accidental assignment bug if you inadvertently use = instead of ==.

pjs
  • 18,696
  • 4
  • 27
  • 56
  • Yep, I've read it already... – Ilan Jul 28 '13 at 20:58
  • 1
    This is a standard llvm compiler warning, though, so there's no real advantage with Objective C. We are fixing all our warnings before testing, right? :) – sapi Jul 28 '13 at 21:00
1

The two forms do exactly the same thing, although the nil == s has one very nice advantage: You'll get a compile error if you make a typo and write = instead of ==, as you can't assign to a constant. This is often referred to as 'Yoda Notation'.

Mike Mertsock
  • 11,825
  • 7
  • 42
  • 75
Kitsune
  • 9,101
  • 2
  • 25
  • 24
  • The name comes from the fact that this notation decreases readibility. With modern compilers you would get a warning anyway – Sulthan Jul 28 '13 at 21:42
  • 1
    @Sulthan I'd agree the value in Objective-C is quite low (thanks to Clang). It's use, though, is much nicer in higher level languages like JavaScript where you don't get any sort of sanity checks like that as part of the normal 'build' process, having to rely on external verifiers (which are rarely integrated into dev environments by default, at least IME). – Kitsune Jul 28 '13 at 22:03