Swift 字典 forEach()

forEach() 方法用于迭代字典中的每个元素。

示例

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

// use forEach() to iterate through a dictionary information.forEach { info in print(info) }
// Output: // (key: "Harvey", value: 38) // (key: "Donna", value: 34) // (key: "Charlie", value: 54)

forEach() 语法

forEach() 方法的语法是:

dictionary.forEach{iterate}

这里,dictionaryDictionary 类的一个对象。


forEach() 参数

forEach() 方法接受一个参数

  • iterate - 一个闭包体,它将字典的元素作为参数。

forEach() 返回值

  • forEach() 方法不返回值。它只迭代字典。

示例 1: Swift 字典 forEach()

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

// use forEach() to iterate through a dictionary information.forEach { info in print(info) }

输出

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

在上面的示例中,我们创建了一个名为 information 的字典,并使用 forEach() 方法对其进行迭代。请注意闭包体,

{ info in 
  print(info)
}

在这里,info 代表 information 的每个元素。在每次迭代中都会打印每个元素。


示例 2: 迭代所有键

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

// iterate through all the keys information.keys.forEach { info in print(info) }

输出

Carlos
Judy
Nelson

在这里,我们使用 keys 属性来迭代 information 字典的所有键

information.keys.forEach {...}

示例 3: 迭代所有值

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

// iterate through all the values information.values.forEach { info in print(info) }

输出

1999
1987
1992

在这里,我们使用 values 属性来迭代 information 字典的所有值

information.values.forEach {...}
你觉得这篇文章有帮助吗?

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

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

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