gpt4 book ai didi

swift - 在 Swift 中使用索引映射或减少

转载 作者:IT王子 更新时间:2023-10-29 04:56:01 29 4
gpt4 key购买 nike

有没有办法在 Swift 的 mapreduce 中获取数组的索引?我正在寻找 Ruby 中类似 each_with_index 的东西。

func lunhCheck(number : String) -> Bool
{
var odd = true;
return reverse(number).map { String($0).toInt()! }.reduce(0) {
odd = !odd
return $0 + (odd ? ($1 == 9 ? 9 : ($1 * 2) % 9) : $1)
} % 10 == 0
}

lunhCheck("49927398716")
lunhCheck("49927398717")

我想去掉 odd 变量 above .

最佳答案

您可以使用enumerate 将序列(ArrayString 等)转换为具有整数计数器的元组序列,并且和元素配对在一起。即:

let numbers = [7, 8, 9, 10]
let indexAndNum: [String] = numbers.enumerate().map { (index, element) in
return "\(index): \(element)"
}
print(indexAndNum)
// ["0: 7", "1: 8", "2: 9", "3: 10"]

Link to enumerate definition

请注意,这与获取集合的索引 不同——enumerate 返回一个整数计数器。这与数组的索引相同,但在字符串或字典上用处不大。要获取每个元素的实际索引,您可以使用 zip:

let actualIndexAndNum: [String] = zip(numbers.indices, numbers).map { "\($0): \($1)" }
print(actualIndexAndNum)
// ["0: 7", "1: 8", "2: 9", "3: 10"]

reduce 中使用枚举序列时,您将无法将元组中的索引和元素分开,因为方法签名中已经有累积/当前元组。相反,您需要在 reduce 闭包的第二个参数上使用 .0.1:

let summedProducts = numbers.enumerate().reduce(0) { (accumulate, current) in
return accumulate + current.0 * current.1
// ^ ^
// index element
}
print(summedProducts) // 56

Swift 3.0 及以上版本

因为 Swift 3.0 语法完全不同。
此外,您可以使用短语法/内联将数组映射到字典:

let numbers = [7, 8, 9, 10]
let array: [(Int, Int)] = numbers.enumerated().map { ($0, $1) }
// ^ ^
// index element

产生:

[(0, 7), (1, 8), (2, 9), (3, 10)]

关于swift - 在 Swift 中使用索引映射或减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28012205/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com