Swift 字典
Swift字典是一个简单的容器,可以以无序的方式包含多个键值对数据。
当您想要在集合中使用某个标识符查找值时,可以使用Swift字典代替数组。假设我们要搜索一个国家的首都。在这种情况下,我们将创建一个以国家为键和首都为值的字典。现在,通过使用国家键进行搜索,您可以从集合中获取首都。在这里,我们将一个国家与其首都配对。
在Swift中声明字典
声明一个空字典
要创建一个空字典,我们在方括号[]中指定键:值的数据类型。
示例
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]
在上面的程序中,我们没有明确声明类型,但是我们初始化了一些默认元素。元素是键值对,键是字符串类型,值是整数类型。 从两个数组创建字典 我们也可以从数组创建字典。 示例:
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中访问字典元素
示例
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"]