在 Swift 中,可以使用enumerated 方法来获取数组中每个元素的序号,然后使用reduce 方法将每个元素和其序号组成的元组转换为字典。

下面是一个示例代码:

let array = ['apple', 'banana', 'orange']

let dictionary = array.enumerated().reduce(into: [Int: String]()) { (result, element) in
    let (index, value) = element
    result[index] = value
}

print(dictionary)

输出结果为:

[0: 'apple', 1: 'banana', 2: 'orange']

在上述代码中,enumerated 方法将数组中的每个元素和其对应的序号组成一个元组。然后,reduce 方法将这些元组转换为字典。初始的结果字典是一个空字典[Int: String](),在每次迭代时,将当前元组中的序号作为键,元素值作为值,添加到结果字典中。最终得到的字典中,键是元素的序号,值是对应的元素值。

Swift 函数式编程:用 enumerated 和 reduce 将数组元素与序号转换为字典

原文地址: https://www.cveoy.top/t/topic/o8Bw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录