Check If Optional Array Is Empty

Check if optional array is empty


Updated answer for Swift 3 and above:

Swift 3 has removed the ability to compare optionals with > and <, so some parts of the previous answer are no longer valid.

It is still possible to compare optionals with ==, so the most straightforward way to check if an optional array contains values is:

if array?.isEmpty == false {
print("There are objects!")
}

Other ways it can be done:

if array?.count ?? 0 > 0 {
print("There are objects!")
}

if !(array?.isEmpty ?? true) {
print("There are objects!")
}

if array != nil && !array!.isEmpty {
print("There are objects!")
}

if array != nil && array!.count > 0 {
print("There are objects!")
}

if !(array ?? []).isEmpty {
print("There are objects!")
}

if (array ?? []).count > 0 {
print("There are objects!")
}

if let array = array, array.count > 0 {
print("There are objects!")
}

if let array = array, !array.isEmpty {
print("There are objects!")
}

If you want to do something when the array is nil or is empty, you have at least 6 choices:

Option A:

if !(array?.isEmpty == false) {
print("There are no objects")
}

Option B:

if array == nil || array!.count == 0 {
print("There are no objects")
}

Option C:

if array == nil || array!.isEmpty {
print("There are no objects")
}

Option D:

if (array ?? []).isEmpty {
print("There are no objects")
}

Option E:

if array?.isEmpty ?? true {
print("There are no objects")
}

Option F:

if (array?.count ?? 0) == 0 {
print("There are no objects")
}

Option C exactly captures how you described it in English: "I want to do something special only when it is nil or empty." I would recommend that you use this since it is easy to understand. There is nothing wrong with this, especially since it will "short circuit" and skip the check for empty if the variable is nil.





Previous answer for Swift 2.x:

You can simply do:

if array?.count > 0 {
print("There are objects")
} else {
print("No objects")
}

As @Martin points out in the comments, it uses func ><T : _Comparable>(lhs: T?, rhs: T?) -> Bool which means that the compiler wraps 0 as an Int? so that the comparison can be made with the left hand side which is an Int? because of the optional chaining call.

In a similar way, you could do:

if array?.isEmpty == false {
print("There are objects")
} else {
print("No objects")
}

Note: You have to explicitly compare with false here for this to work.


If you want to do something when the array is nil or is empty, you have at least 7 choices:

Option A:

if !(array?.count > 0) {
print("There are no objects")
}

Option B:

if !(array?.isEmpty == false) {
print("There are no objects")
}

Option C:

if array == nil || array!.count == 0 {
print("There are no objects")
}

Option D:

if array == nil || array!.isEmpty {
print("There are no objects")
}

Option E:

if (array ?? []).isEmpty {
print("There are no objects")
}

Option F:

if array?.isEmpty ?? true {
print("There are no objects")
}

Option G:

if (array?.count ?? 0) == 0 {
print("There are no objects")
}

Option D exactly captures how you described it in English: "I want to do something special only when it is nil or empty." I would recommend that you use this since it is easy to understand. There is nothing wrong with this, especially since it will "short circuit" and skip the check for empty if the variable is nil.

Check if optional array is empty in Swift

You could unwrap the optional array and use that like this, also use the new Int.random(in:) syntax for generating random Ints:

if let unwrappedArray = quotearray,
!unwrappedArray.isEmpty {
let item = unwrappedArray[Int.random(in: 0..<unwrappedArray.count)]
}

Checking if array is nil or not

Just use ??.

if !(listCountries ?? []).isEmpty {

However, since you want to probably use listCountries in the if block, you should unwrap

if let listCountries = self.listCountries, !listCountries.isEmpty {

Ideally, if nil and empty means the same to you, don't even use an optional:

var listCountries: [Countries] = []

Check if an array is empty or exists


if (typeof image_array !== 'undefined' && image_array.length > 0) {
// the array is defined and has at least one element
}

Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable:

<?php echo "var image_array = ".json_encode($images);?>
// add var ^^^ here

And then make sure you never accidently redeclare that variable later:

else {
...
image_array = []; // no var here
}

How to check for an empty Optional array of strings in Java?

Optional<String>[] is an array of Optional<String> elements.

You'd rather want to have optional array of strings, so you need to change paramArray type to Optional<String[]>.

@PostMapping("/users")
@ResponseBody
public String saveUsers(@RequestParam Optional<String[]> paramArray) {
System.out.println("param " + paramArray);
String msg = "";
int i = 0;
if (paramArray.isEmpty()) {
msg = "paramArray is empty";
} else {
for (String paramArrayItem : paramArray.get()) {
msg += "param[" + i + "]" + paramArrayItem + "\n";
i++;
}
}
return msg;
}

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
// array does not exist or is empty
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach

Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ⇒ do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.

    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach

In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}

Or the opposite:

if (array?.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}

How to create an empty, optional array?

If you really want to do it:

var myArray: [String]? = []

Array literals are denoted by []. not (). () is an empty tuple.

However, as people have mentioned in the comments, this is an anti-pattern. If an "empty array" and "nil" don't mean something different to your code, then just use a regular [String], and use an empty array to indicate "nothing".

Also from the comments, you seem to be trying to write Swift code the way you write your Java code. I suggest you don't do that. When in Rome, do as the Romans do :)

How to check if array is null or empty?


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

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



Related Topics



Leave a reply



Submit