📜  Swift字典

📅  最后修改于: 2021-01-11 07:49:37             🧑  作者: Mango

斯威夫特字典

Swift字典是一个简单的容器,可以无序包含多个数据作为键值对。

当您要在集合中查找带有某些标识符的值时,将使用Swift字典而不是数组。假设我们必须搜索国家的首都。在这种情况下,我们将创建一个包含主要国家和价值首都城市的字典。现在,您可以通过搜索关键国家来从集合中获取首都。在这里,我们已将一个国家与其首都配对。

Swift中的字典声明

声明一个空字典

要创建一个空字典,我们在方括号[]中指定key:value数据类型。

例:

let emptyDictionary:[Int:String] = [:]
print(emptyDictionary)

要么

let emptyDictionary:Dictionary = [:]
print(emptyDictionary)

输出:

[:]

声明具有某些值的字典

let valDictionary = ["a":10, "b":20, "c":30, "d":40, "e":50, "f":60, "g":70, "h":80, "i":90]
print(valDictionary)

输出:

["c": 30, "d": 40, "g": 70, "b": 20, "a": 10, "f": 60, "h": 80, "i": 90, "e": 50]

在上面的程序中,我们没有显式声明类型,但是我们使用一些默认元素进行了初始化。元素位于key:value对中,其中key的类型为String,而value的类型为Int。

从两个数组创建字典

我们还可以从数组创建字典。

例:

let customKeys = ["India", "Pakistan", "United Kingdom"]
let customValues = ["New Delhi", "Islamabad", "London"]
let newDictionary = Dictionary(uniqueKeysWithValues: zip(customKeys,customValues))
print(newDictionary)

输出:

["India": "New Delhi", "United Kingdom": "London", "Pakistan": "Islamabad"]

在Swift中访问字典元素

我们可以通过在字典名称之后立即在方括号内包含要访问的值的键来访问Swift字典的元素。

例:

let valDictionary = ["a":10, "b":20, "c":30, "d":40, "e":50, "f":60, "g":70, "h":80, "i":90]
print(valDictionary["c"])
print(valDictionary["f"])

输出:

Optional(30)
Optional(60)

使用for-in循环访问Swift中的Dictionary元素

例:

let valDictionary = ["a":10, "b":20, "c":30, "d":40, "e":50, "f":60, "g":70, "h":80, "i":90]
for (key,value) in valDictionary {
    print("key:\(key) value:\(value)")
}

输出:

key:h value:80
key:d value:40
key:a value:10
key:g value:70
key:e value:50
key:b value:20
key:c value:30
key:f value:60
key:i value:90

在Swift中修改字典元素

我们可以通过使用新的键作为索引在Swift字典中添加新元素并分配给新值。

例:

var valDictionary = ["India":"New Delhi", "China":"Beijing", "USA":"Washington D.C."]
valDictionary["Germany"] = "Berlin"
print(valDictionary)

输出:

["Germany": "Berlin", "China": "Beijing", "USA": "Washington D.C.", "India": "New Delhi"]

更改字典中的元素

例:

var valDictionary = ["India":"New Delhi", "China":"Beijing", "USA":"Washington D.C."]
valDictionary["India"] = "NEW DELHI"
print(valDictionary)

输出:

["USA": "Washington D.C.", "China": "Beijing", "India": "NEW DELHI"]