How to count the elements of an Array in Swift?
In Swift, 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. An array 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 can count the elements of the array. To do this we use the count property of the array. This property is used to count the total number of values available in the specified array.
Syntax:
arrayName.count
Here,
arrayName is the object of the array class.
Return Value: It will return the total number of values present in the given array.
Example 1:
Swift
// Swift program to find the total number of elements in the array import Swift // Creating an array of Authors Name // Here the array is of string type var AuthorName = [ "Tina" , "Prita" , "Mona" , "Guri" , "Om" , "Rohit" ] // Finding the total number var result1 = AuthorName. count // Displaying the result print ( "Total number of authors:" , result1) // Creating an empty array of GEmployee Name // Here the array is of string type var GEmployee = [ Int ]() // Finding the total number var result2 = GEmployee. count // Displaying the result print ( "Total number of Gemployees:" , result2) |
Output:
Total number of authors: 6 Total number of Gemployees: 0
Example 2:
Swift
// Swift program to find the total number of elements in the array import Swift // Creating an array of Authors Name // Here the array is of string type var AuthorName = [ "Tina" , "Prita" , "Mona" , "Guri" , "Om" , "Rohit" ] // Using count property if (AuthorName. count > 3) { print ( "Array contains more authors name" ) } else { print ( "Array contains less authors name" ) } |
Output:
Array contains more authors name
Contact Us