Introduction
This is part four of "Swift Programming - Zero to Hero" series. You can read the previous articles in the series here:
In this article, we will learn about -
- Arrays
- Accessing Arrays Using Looping Statements
Arrays
An array is a collection of similar items in an ordered list. The same items can appear multiple times at different positions in an array.
Syntax
var variableName = [item1,item2…..itemN]
Example
var ArrayElements=[1,2,3,4,5]
From the above example, ArrayElements is the Variable name of the Array, i.e., Array Name and 1,2,3,4,5 are the array elements or items in the array. There are five array elements starting from position 0 [Zero]. This array is Integer Array because it consists of integer values. Let us see another example of String arrays.
Example
var Names=[“Sundar”,”Raj”,”Sarwan”,”karthik,”Linga”]
From the above given example, names in the array and array elements are sundar, Raj, Sarwan, Karthik, Linga. The array’s type is String.
Accessing Arrays using Looping Statements
Here, we will learn accessing elements using,
For Loop
Syntax
var varaibleName=[item1,item2,item3…..itemN]
for (init;condition;loop expression){
statements
}
Example
- var Names = [“Sundar”, ”Raj”, ”Sarwan”, ”karthik, ”Linga”]
- for (var i = 0; i < 3; ++i)
- {
- println(“The First Three Names are” Name[i])
- }
Output
The First Three Names are Sundar
The First Three Names are Raj
The First Three Names are Sarwan
In the above example, I have declared a String array with five elements. In for loop, I have initialized i as 0 and conditioned it to execute upt o 3, so, the first three elements are iterated and displayed.
For In Loop
Syntax
var varaibleName=[item1,item2,item3…..itemN
for index in var {
statement(s)
}
Example
- var Names = [“Sundar”, ”Raj”, ”Sarwan”, ”karthik, ”Linga”]
- for names in Names
- {
- println(names)
- }
Output
Sundar
Raj
Sarwan
Karthik
Linga
In the above example, I have selected all the elements in the array using for-in loop.
Conclusion
In this article, we have learned arrays and accessing array elements. Hope this article was useful.