User1238
User1238

Reputation: 87

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)

Upvotes: 1

Views: 94

Answers (4)

iamyogish
iamyogish

Reputation: 2432

From your comment, I assume you're trying to read the Country names to the variable "l".

Try with this code snippet,

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

var l:String?
//You need to assign an initial value to l before you start appending country names.
//If you don't assign an initial value, the value of variable l will be nil as it is an optional.
//If it is nil, l? += value which will be executed as optional chaining will not work because optional chaining will stop whenever nil is encountered.
l = ""

for (key, value) in LandsDictionary{
    l? += value
}
print (l)

Hope this helps.

Upvotes: 1

vadian
vadian

Reputation: 285260

Since all keys and values are non-optional in this dictionary, there is not need to use optional variables.

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

var l = ""

// the underscore represents the unused key
for (_, land) in landsDictionary {
  l += land
}
print (l) // "GermanyFrance"

or without a loop

let v = Array(landsDictionary.values).joinWithSeparator("")
print (v) // "GermanyFrance"

Upvotes: 3

Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

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

Upvotes: 0

good4pc
good4pc

Reputation: 711

For iterating a dictionary

 for (key , value) in LandsDictionary{
                print(key)
                print(value)
            }

Upvotes: 0

Related Questions