Check if an array is empty or not in Swift


In this Swift programming tutorial, you are going to learn how to check if a Swift array is empty or not with examples.

In Swift, we can use the built-in isEmpty property to check out if our array is empty. Below is a simple example of using this property:

myArray.isEmpty

In the above example, myArray is the variable name or constant name of the array to be checked. It will return either true or false.

If the array is empty, then it will return boolean true otherwise, it will return boolean false.

Now let’s look at a proper example:

var animals = ["Lion", "Elephant", "Tiger", "Horse"]

var checkEmpty = animals.isEmpty

print(checkEmpty)

Output:

False

Using isEmpty with if...else

Now see another example of using the isEmpty property with the if...else statement to check if an array is empty or not:

var animals = String()

if (animals.isEmpty) {
  print("Array is empty")
}
else {
  print("Array is not empty")
}

Output:

Array is empty

Using isEmpty with the switch statement

We can also use the isEmpty property with the switch statement in Swift. Below is how we can do it:

var numbers = [7, 9, 3, 1]

switch (numbers.isEmpty)  {
  case true:
    print("Array is empty")
  case false:
    print("Array is not empty")
}

Output:

Array is not empty