1

The answer chosen here states that it checks if the array is not empty. And if it is not empty, that means the code should be executed.

How to check if array is null or empty?

However, I am seeing the opposite. When I use if (!array.count) with a non empty array, the code within is not executed. If I use if (array.count) with a non empty array, the code within is executed. What am I missing here?

James
  • 53
  • 11
  • 2
    You probably know that numerically 0 equals false and anything else equals true. Now take that logic and think what happens when the array has zero elements and when it has one element. – Confuzing Mar 15 '18 at 19:54

1 Answers1

3

The code in that answer is correct for the question being asked. It's the text in the answer that is confusing. The goal of that question is to see if an array is "empty". The accepted answer has the code:

if (!array || !array.count){
}

The text in that answer states:

That checks if array is not nil, and if not - check if it is not empty.

But that if statement actually means "if the array is nil or the array count is zero, do something". So it's the exact opposite.

So the code is correct but the text is wrong (or at least misleading).

Back to your own question.

if (array.count) {
    // same as array.count != 0
    // array is not empty (non-zero count)
}

or:

if (!array.count) {
    // same as !(array.count != 0) or array.count == 0
    // array is empty (zero count)
}

Remember, in C, C++, Objective-C, an if statement is treated as "true" if the expression evaluates to a non-zero value and "false" is it evaluates to zero. And the use of ! at the start negates the "true" to "false" or the "false" to "true".

rmaddy
  • 314,917
  • 42
  • 532
  • 579