Swift 字典 enumerated()

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

示例

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

// use enumerated() to iterate through a dictionary for (index, key_value) in information.enumerated() {
print("\(index): \(key_value)") } // Output: // 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()

// create a dictionary with three elements
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]

// use enumerated() to iterate through a dictionary 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:仅访问键值对

// create a dictionary with three elements
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]

// use enumerated() to iterate through a dictionary 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() { ... }

这里,我们使用下划线 _ 代替变量名,以便在不使用索引值的情况下遍历键值对。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战