TagDictionary

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 – Dictionary

 

Dictionary in swift are used to key value pairs of some data type. The syntax for dictionary in swift is as shown below.

var (or let for constant) myFirstDictionary = [Key:value.. Key:Value]

Some example dictionaries are shown below.

var myFirstDictionary = [:]
println("myFirstDictionary:\(myFirstDictionary)")
var mySecondDictionary = ["Key1":"Value1","Key2":"Value2"]
println("mySecondDictionary:\(mySecondDictionary)")
var myThirdDictionary:Dictionary = ["Key1":"Value1","Key2":"Value2"]
println("myThirdDictionary:\(myThirdDictionary)")
var myOptionalFourthDictionary:Array?
println("myOptionalFourthDictionary:\(myOptionalFourthDictionary)")

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

myFirstDictionary:{
}
mySecondDictionary:[Key2: Value2, Key1: Value1]
myThirdDictionary:[Key2: Value2, Key1: Value1]
myOptionalFourthDictionary:nil

Adding Values to an Dictionary

In array, adding values is made easy with the use simple hashing structure. An example is shown below

var myDictionary:Dictionary = [:]
myDictionary["Key1"] = "New Value 1"
println("myDictionary:\(myDictionary)")

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

myDictionary:[Key1: New Value 1]