Check if Array is Empty in Swift

The Swift code example below demonstrates a couple of ways how to check if an Array of elements is empty. To be a little more specific this code will demonstrate how to:

  • Create an array with 5 elements,
  • Remove all elements from Array,
  • Check if Array is empty,
  • Check if the number of elements in the Array is greater than zero.
// Initialize Array with 5 elements
var myArray = [1, 2 , 3, 4, 5]
// Remove all elements from an array
myArray.removeAll()
// Check if Array is empty
if myArray.isEmpty {
    print("Array is empty")
} else {
    print("Array is not empty")
}
// Another way to check if Array is empty
if myArray.count > 0 {
    print("Array is empty")
} else {
    print("Array is not empty")
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published. Required fields are marked *