TagArrays

Swift for loop statement

Simple for statement

A simple for statement consists of an initializer, condition and an increment/decrement. In the following example, we have an variable i initialized to 0 and we check for a condition i<2 and use an increment i++. This i++ could be i+1 or i-2 and so on. It depends on your need.

for(var i = 0; i<2; i++){
    println(i)
}

Output

0
1

for in with dictionaries

We can access an key value of dictionaries with for in statement. A simple example is shown below.

var dict = ["1":"Eezy", "2":"Tutorials"]
for (key,value) in dict
{
    println("\(key) : \(value)")
}

Output

2 : Tutorials
1 : Eezy

for in with arrays

We can access an array of values with for in statement. A simple example is shown below.

var array = ["Eezy", "Tutorials"]
for value in array
{
    println(value)
}

Output

Eezy
Tutorials

for in with ranges

Ranges provides more power to for. You can just specify the starting and finishing values of a range. A simple example is given below. The range includes the starting and ending number

for i in 0...3
{
    println(i)
}

Output

0
1
2
3

 

Swift – Arrays

 

Arrays in swift are used to store values of same data type. The syntax for arrays in swift is as shown below.

var (or let for constant) myFirstArray = [values]

Some example arrays are shown below.

var myFirstArray = []
println("myFirstArray:\(myFirstArray)")
var mySecondArray = ["Value1","Value2"]
println("mySecondArray:\(mySecondArray)")
var myThirdArray:Array = ["Value1","Value2"]
println("myThirdArray:\(myThirdArray)")
var myOptionalFourthArray:Array?
println("myOptionalFourthArray:\(myOptionalFourthArray)")

When you run the above program, we will get the following output.

myFirstArray:(
)
mySecondArray:[Value1, Value2]
myThirdArray:[Value1, Value2]
myOptionalFourthArray:nil

Adding Values to an array

In array, adding values is made easy with the use of += operator overloading. You also have append method and insert methods for inserting to array. An example is shown below

var myArray:Array = []
myArray += ["New Value 1"]
myArray += ["New Value 2"]
println("myArray:\(myArray)")

When you run the above program, we will get the following output.

myArray:[New Value 1, New Value 2, New Value 4, New Value 3]