Swift Programming - Zero To Hero - Part Four

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 -

  1. Arrays
  2. 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,

  1. for loop
  2. for in loop

For Loop

Syntax

var varaibleName=[item1,item2,item3…..itemN]

for (init;condition;loop expression){

statements

}

Example

  1. var Names = [“Sundar”, ”Raj”, ”Sarwan”, ”karthik, ”Linga”]  
  2. for (var i = 0; i < 3; ++i)   
  3. {  
  4.     println(“The First Three Names are” Name[i])  
  5. }  

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

  1. var Names = [“Sundar”, ”Raj”, ”Sarwan”, ”karthik, ”Linga”]  
  2. for names in Names  
  3. {  
  4.     println(names)  
  5. }  

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.

Up Next
    Ebook Download
    View all
    Learn
    View all