mapValues()
方法通过将相同的操作应用于字典中的每个值来转换字典。
示例
var multiply = ["first": 1, "second": 2, "third": 3]
// multiply each dictionary value by 2
var result = multiply.mapValues({$0 * 2})
print(result)
// Output: ["first": 2, "second": 4, "third": 6]
mapValues() 语法
mapValues()
方法的语法是
dictionary.mapValues({transform})
这里,dictionary 是 Dictionary
类的一个对象。
mapValues() 参数
mapValues()
方法接受一个参数
- transform - 一个闭包体,描述了要对每个值进行的转换类型。
mapValues() 返回值
- 返回一个新字典,其中包含 dictionary 的键以及通过给定闭包转换的新值。
示例 1:Swift 字典 mapValues()
var number = ["first": 10, "second": 20, "third": 30]
// add 20 to each value
var result = number.mapValues({ $0 + 20})
print(result)
输出
["third": 50, "first": 30, "second": 40]
在上面的示例中,我们使用 mapValues()
方法转换了 number 字典。请注意闭包的定义,
{ $0 + 20 }
这是一个简写的闭包,将 number 的每个值增加 20。
$0
是指向传递到闭包的第一个参数的快捷方式。
最后,我们打印了新的字典,其中包含 number 的键以及与每个键关联的新值。
示例 2:使用 mapValues() 将字符串字典转换为大写
var employees = [1001: "tracy", 1002: "greg", 1003: "Mason"]
// uppercase each value of employees
var result = employees.mapValues({ $0.uppercased()})
print(result)
输出
[1002: "GREG", 1001: "TRACY", 1003: "MASON"]
在上面的示例中,我们使用了 mapValues()
和 uppercased()
方法来转换 employees 字典的每个值。
uppercased()
方法将字典的每个字符串值转换为大写。