User1238 User1238 - 3 months ago 9
Swift Question

Iterating in a dictionary with swift

I am learning swift and I am trying to iterate in a dictionary. Can you please tell me why the variable l is nil at the end

let LandsDictionary = ["DE":"Germany", "FR":"France"]

var l:String?

for land in LandsDictionary{
l?+=land
}
print (l)

Answer

It is example how you can get keys and values in two different ways. Try to read about collection bit more.

let LandsDictionary = ["DE":"Germany", "FR":"France"]

var keys :String = ""

var values :String = ""

//Iteration is going on properly and fetching key value.
for land in LandsDictionary {

    print (land) // "DE":"Germany" and "FR":"France"

    keys += land.0

    values +=  land.1
}

//All keys
print(keys)

//All values
print(values)

//If you would like to recive all values and all keys use standart method of the collection.

let allKeys = LandsDictionary.keys

let allValues = LandsDictionary.values
Comments