OneBite.Dev - Coding blog in a bite size

Check If Array Is Empty In Swift

Code snippet for how to Check If Array Is Empty In Swift with sample and detail explanation

Swift, a programming language developed by Apple, offers an easy and convenient way to check if an array is empty. This method is particularly useful in a variety of coding scenarios.

Code snippet to Check If Array Is Empty In Swift

Here is a basic example of how to check if an array is empty in Swift.

let numbers = [Int]()

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

Code Explanation for Checking If Array Is Empty In Swift

In this example, we have an array named “numbers” which is an array of integers. When declaring the array, we haven’t added any elements to it hence it is empty.

The syntax [Int]() creates an empty array of type Int.

The isEmpty property is a default property available in Swift for all arrays. This property returns a Boolean value. If there are no elements in the array, isEmpty returns true, otherwise, it will return false.

To validate if our array “numbers” has any elements or not, we use an if statement combined with isEmpty, as shown in the code above.

The if numbers.isEmpty {} condition checks whether the array is empty. If the array is empty, it will execute the code within the curly brackets {}, which in this case, is print("Array is empty.").

In the case of our example, when the numbers array is empty, the application will print “Array is empty.”

On the other hand, if the array is not empty, then the code inside the else block will execute, printing “Array is not empty.”

That’s the way you check if an array is empty or not in Swift. Really straightforward and easy to implement in your code when needed.

swift