Swift 字典 max() 方法
max()
方法返回字典中的最大键-值对。
示例
let studentsHeights = ["Sabby": 180.6, "Dabby": 170.3, "Cathy": 156]
// 比较值并返回最大的键-值对
let maximumHeight = studentsHeights.max { $0.value < $1.value }
print(maximumHeight!)
// 输出: (key: "Sabby", value: 180.6)
max() 语法
字典 max()
方法的语法如下:
dictionary.max {operator}
这里,dictionary
是 dictionary
类的对象。
max() 参数
max()
方法可以接受一个参数:
- operator - 一个接受条件并返回 Bool 值的闭包。
max() 返回值
max()
方法返回 dictionary
中的最大元素。
注意: 如果 dictionary
是空的,该方法将返回 nil
。
示例1:Swift 字典的 max() 方法
let fruitPrice = ["Grapes": 2.5, "Apricot": 3.5 , "Pear": 1.6]
// 通过比较值并返回最大的键-值对
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]
// 通过比较键并返回最大的键-值对
let maximumPrice = fruitPrice.max { $0.key < $1.key }
print(maximumPrice!)
输出
(key: "Pear", value: 1.6)
在这里,我们使用 key
属性来比较 fruitPrice
字典的所有键:
{ $0.key < $1.key }