跳到主要内容

Swift字典的mapValues()方法

mapValues() 方法通过将相同的操作应用于字典中的每个值来转换字典。

示例

var multiply = ["first": 1, "second": 2, "third": 3]

// 将字典中的每个值乘以2
var result = multiply.mapValues({$0 * 2})

print(result)

// 输出: ["first": 2, "second": 4, "third": 6]

mapValues() 语法

mapValues() 方法的语法如下:

dictionary.mapValues({transform})

这里,dictionaryDictionary 类的对象。

mapValues() 参数

mapValues() 方法接受一个参数:

  • transform - 描述要对每个值执行的转换类型的闭包体。

mapValues() 返回值

  • 返回一个新的字典,其中包含由给定闭包转换的dictionary中的键和新值。

示例 1:Swift 字典 mapValues()

var number = ["first": 10, "second": 20, "third": 30]

// 将每个值加20
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"]

// 将 employees 字典中的每个值都转换为大写
var result = employees.mapValues({ $0.uppercased()})

print(result)

输出

[1002: "GREG", 1001: "TRACY", 1003: "MASON"]

在上面的示例中,我们使用了mapValues()uppercased()方法来转换employees字典的每个值。

uppercased()方法将字典的每个字符串值转换为大写。