Swift 字典 max()

max() 方法返回字典中键值对最大的项。

示例

let studentsHeights = ["Sabby": 180.6, "Dabby": 170.3, "Cathy": 156]

// compare the values and return maximum key-value pair let maximumHeight = studentsHeights.max { $0.value < $1.value }
print(maximumHeight!) // Output: (key: "Sabby", value: 180.6)

max() 语法

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

dictionary.max {operator}

这里,dictionarydictionary 类的一个对象。


max() 参数

max() 方法可以接受一个参数:

  • operator - 一个闭包,它接受一个条件并返回一个 Bool 值。

max() 返回值

max() 方法返回 dictionary 中的最大元素。

注意:如果 dictionary 为空,则该方法返回 nil


示例 1:Swift 字典 max()

let fruitPrice = ["Grapes": 2.5, "Apricot": 3.5 , "Pear": 1.6]

// compares the values and return maximum key-value pair let maximumPrice = fruitPrice.max { $0.value < $1.value }
print(maximumPrice!)

输出

(key: "Apricot", value: 3.5)

在上面的示例中,我们传递了一个闭包来通过比较 fruitPrice 中的所有值来查找键值对最大的项。注意闭包的定义:

{ $0.value < $1.value }

这是一个简写闭包,用于检查 fruitPrice 的第一个值是否小于第二个值。

$0$1 是指传递给闭包的第一个和第二个参数的快捷方式。

由于 max() 方法是可选的,我们使用 ! 对其进行了强制解包。


示例 2:比较键并返回值

let fruitPrice = ["Grapes": 2.5, "Apricot": 3.5 , "Pear": 1.6]

// compares the keys and return maximum key-value pair let maximumPrice = fruitPrice.max { $0.key < $1.key }
print(maximumPrice!)

输出

(key: "Pear", value: 1.6)

在这里,我们使用了 key 属性来比较 fruitPrice 字典的所有键

{ $0.key < $1.key }
你觉得这篇文章有帮助吗?

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

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

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