Open In App

How to check if an array is empty in Swift?

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Swift language supports different collections like a set, array, dictionary, etc. An array is an ordered generic collection that is used to keep the same type of data like int, float, string, etc., here you are not allowed to store the value of another type. It also keeps duplicate values of the same type. It can be mutable and immutable. When we assign an array to a variable, then that array is known as mutable whereas when we assign an array to a constant, then that array is known as immutable. In the Swift array, we check if the given array is empty or not using the isEmpty property. This property is used to find whether the given array is empty or not. If the given array is empty then this property will return true otherwise it will return false. 

Syntax:

arrayName.isEmpty

Here, 

arrayName is the object of the array class.

Return Value: This property will return true if the given array is empty or return false if the given array contains elements.

Example 1:

Swift




// Swift program to check if the given array
// is empty or not
import Swift
  
// Creating an array of EmployeeSalary
// Here the array is of int type
var GEmpSalary = [34, 122, 14, 678, 1, 90]
  
// Checking the given array is empty or not
// Using isEmpty property
var result1 = GEmpSalary.isEmpty
  
// Displaying the result
print("Is the GEmpSalary is empty or not?", result1)
  
// Creating an empty array of int type
var GEmployee = [Int]()
  
// Finding the total number
var result2 = GEmployee.isEmpty
  
// Displaying the result
print("Is the GEmployee is empty or not?", result2)


Output:

Is the GEmpSalary is empty or not? false
Is the GEmployee is empty or not? true

Example 2:

Swift




// Swift program to check if the given array is empty or not
import Swift
  
// Creating an array of Authors Name
// Here the array is of string type
var AuthorName = ["Tina", "Prita", "Mona", "Guri", "Om", "Rohit"]
  
// Checking the given array is empty or not
// Using isEmpty property
if (AuthorName.isEmpty == true)
{
    print("Yes! the given Array is empty")
}
else
{
    print("No! the given array is not empty")
}


Output:

No! the given array is not empty


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads