跳到主要内容

Swift 字典 enumerated() 方法

enumerated()方法用于遍历字典的键值对。

示例

var information = ["Charlie": 54, "Harvey": 38, "Donna": 34]

// 使用enumerated()来遍历字典
for (index, key_value) in information.enumerated() {
print("\(index): \(key_value)")
}

// 输出:
// 0: (key: "Donna", value: 34)
// 1: (key: "Charlie", value: 54)
// 2: (key: "Harvey", value: 38)

enumerated()语法

字典enumerated()方法的语法如下:

dictionary.enumerated{iterate}

这里,dictionaryDictionary类的对象。

enumerated()参数

enumerated()方法接受一个参数:

  • iterate - 一个接受dictionary的元素作为参数的闭包。

enumerated()返回值

  • enumerated()方法返回一个带有它们的索引值的键值对序列。

示例 1:Swift字典enumerated()

// 创建一个包含三个元素的字典
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]

// 使用enumerated()来遍历字典
for (index, key_value) in information.enumerated() {
print("\(index): \(key_value)")
}

输出

0: (key: "Judy", value: 1992)
1: (key: "Nelson", value: 1987)
2: (key: "Carlos", value: 1999)

在上面的示例中,我们创建了一个名为information的字典,并使用enumerated()方法来遍历它。注意使用forenumerated()方法,

for (index, key_value) in information.enumerated() {
print("\(index): \(key_value)")
}

这里,index表示每个键值对的索引值,key_value表示information的每个键值对。

示例 2:仅访问键值对

// 创建一个包含三个元素的字典
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]

// 使用enumerated()来遍历字典
for (_, key_value) in information.enumerated() {
print("\(key_value)")
}

输出

(key: "Nelson", value: 1987)
(key: "Carlos", value: 1999)
(key: "Judy", value: 1992)

在上面的示例中,我们使用enumerated()方法来遍历键值对。注意以下行,

for (_, key_value) in information.enumerated() { ... }

这里,我们使用下划线 _ 代替变量名来遍历键值对,而不包括它们的索引值。