How to count the elements of an Array in Swift?
Last Updated :
02 Jun, 2022
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
import Swift
var AuthorName = [ "Tina" , "Prita" , "Mona" , "Guri" , "Om" , "Rohit" ]
var result1 = AuthorName. count
print ( "Total number of authors:" , result1)
var GEmployee = [ Int ]()
var result2 = GEmployee. count
print ( "Total number of Gemployees:" , result2)
|
Output:
Total number of authors: 6
Total number of Gemployees: 0
Example 2:
Swift
import Swift
var AuthorName = [ "Tina" , "Prita" , "Mona" , "Guri" , "Om" , "Rohit" ]
if (AuthorName. count > 3)
{
print ( "Array contains more authors name" )
}
else
{
print ( "Array contains less authors name" )
}
|
Output:
Array contains more authors name
Share your thoughts in the comments
Please Login to comment...