用swift在字典中迭代

时间:2016-08-10 10:15:47

标签: swift dictionary optional

我正在学习swift,我正在尝试迭代字典。你能否告诉我为什么变量l最后为零

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

var l:String?

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

4 个答案:

答案 0 :(得分:3)

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

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"

答案 1 :(得分:1)

从您的评论中,我假设您正在尝试将国家/地区名称读取为变量“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)

希望这有帮助。

答案 2 :(得分:0)

用于迭代字典

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

答案 3 :(得分:0)

这是如何以两种不同的方式获取键和值的示例。尝试更多地了解收集。

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