使用 swift 在字典中迭代

Iterating in a dictionary with swift

我正在学习 swift 并且我正在尝试在字典中进行迭代。你能告诉我为什么变量 l 最后是 nil

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

var l:String?

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

用于迭代字典

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

根据您的评论,我假设您正在尝试将国家/地区名称读取到变量 "l"。

试试这个代码片段,

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)

希望对您有所帮助。

这是如何以两种不同方式获取键和值的示例。试着多读一点 collection。

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

由于本字典中的所有键和值都是非可选的,因此不需要使用可选变量。

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

var l = ""

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

或没有循环

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