Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift Array count
In this tutorial, we will learn about the Swift array count property with the help of examples.
The count property returns the total number of elements present in the array.
Example
var languages = ["Swift", "C", "Java"]
// count total number of elements in languages
var result = languages.count
print(result)
// Output: 3
count Syntax
The syntax of the array count property is:
array.count
Here, array is an object of the Array class.
count Return Values
The count property returns the total number of elements present in the array.
Example 1: Swift Array count
var names = ["Gregory", "Perry", "Nadal"]
// count total elements on names
print(names.count)
var employees = [String]()
// count total elements on employees
print(employees.count)
Output
3 0
In the above example, since
- names contain three string elements, the property returns 3.
- employees is an empty array, the property returns 0.
Example 2: Using count With if...else
var numbers = [1,2,3,4,5,6,7,8,9,10]
// true because there are 10 elements on numbers
if (numbers.count > 5) {
print( "The array size is large")
}
else {
print("The array size is small")
}
Output
The array size is large
In the above example, we have created the array named numbers with 10 elements.
Here, since there are 10 elements in the array, numbers.count > 5 evaluates to true, so the statement inside the if block is executed.
Did you find this article helpful?