Swift 中的字典迭代
我们可以使用多种方法在 Swift 中迭代字典。您也可以迭代字典的键和值。
我们将使用以下不同的方法来迭代字典:
使用 for-in 循环
迭代字典中的所有键
迭代字典中的所有值
使用 enumerated() 方法迭代所有元素
使用 for-in 循环
大多数情况下,我们使用 for-in 循环来迭代字典。使用 for-in 循环,您可以像下面这样迭代字典的所有元素:
语法
for (key, value) in dictionary { }
在语法中,key 和 value 是将分别保存当前键和值的变量的名称。
示例
import Foundation let colorsDictionary = [ "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aqua": "#00ffff", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "black": "#000000", "blanchedalmond": "#ffebcd", "blue": "#0000ff", "blueviolet": "#8a2be2", "brown": "#a52a2a" ] for (colorName, colorValue) in colorsDictionary { print("Name: \(colorName) and its hex code: \(colorValue)") }
输出
Name: brown and its hex code: #a52a2a Name: bisque and its hex code: #ffe4c4 Name: blueviolet and its hex code: #8a2be2 Name: aqua and its hex code: #00ffff Name: aliceblue and its hex code: #f0f8ff Name: aquamarine and its hex code: #7fffd4 Name: azure and its hex code: #f0ffff Name: beige and its hex code: #f5f5dc Name: blanchedalmond and its hex code: #ffebcd Name: blue and its hex code: #0000ff Name: antiquewhite and its hex code: #faebd7 Name: black and its hex code: #000000
在上面的示例中,我们创建了一个字典来定义一些颜色及其名称和十六进制值。使用 for-in 循环,逐个迭代所有元素,顺序未指定。它以 (键, 值) 对的形式给出元素。
迭代所有键
如果您想一次访问或迭代所有键,可以使用“keys”属性。此属性返回一个字符串类型的数组,其中包含字典的所有键。
示例
import Foundation let colorsDictionary = ["aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aqua": "#00ffff", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "black": "#000000", "blanchedalmond": "#ffebcd", "blue": "#0000ff", "blueviolet": "#8a2be2", "brown": "#a52a2a" ] for key in colorsDictionary.keys { print("Key: \(key)") }
输出
Key: brown Key: antiquewhite Key: bisque Key: beige Key: black Key: aqua Key: azure Key: aliceblue Key: blue Key: blueviolet Key: aquamarine Key: blanchedalmond
在上面的示例中,我们创建了一个字典来定义一些颜色及其名称和十六进制值。使用 for-in 循环迭代字典的所有键。
迭代所有值
如果您想一次访问或迭代所有值,可以使用“values”属性。此属性返回一个字符串类型的数组,其中包含字典的所有值。
示例
import Foundation let colorsDictionary = ["aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aqua": "#00ffff", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "black": "#000000", "blanchedalmond": "#ffebcd", "blue": "#0000ff", "blueviolet": "#8a2be2", "brown": "#a52a2a" ] for value in colorsDictionary.values { print("Value: \(value)") }
输出
Value: #00ffff Value: #f0f8ff Value: #f5f5dc Value: #000000 Value: #f0ffff Value: #ffebcd Value: #7fffd4 Value: #ffe4c4 Value: #0000ff Value: #faebd7 Value: #a52a2a Value: #8a2be2
结论
我们可以迭代 Swift 中字典的元素、键和值。字典提供“keys”属性来访问所有键的数组。同样,“values”属性提供所有值的数组。
您可以使用 for-in 循环和其他方法迭代字典。但请记住,元素的顺序未指定。但是,使用 enumerated() 函数,您仍然可以在访问元素时跟踪其索引。
广告