有没有办法在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")

我想go 掉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

请注意,这与获取集合的index不同——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 and above

因为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相关问答推荐

运行异步任务串行运行

ARRaycast Query和前置摄像头(ARFaceTrackingConfiguration)

当计数大于索引时,索引超出范围崩溃

是否可以将具有关联值的枚举强制转换为其类型与关联值匹配的变量?

同时具有每个文本的标识符的文本组的可扩展性标识符

按数组大小进行类型判断?

当将新值推送到 NavigationStack 时,SwiftUI 的 navigationDestination 已在堆栈的早期声明

Swift计时器未触发

如何使一个 Reality Composer 场景中的分组对象可拖动?

如何判断一个值是否为 Int 类型

快速更改tableView中的数据

UUID 哈希值是不确定的吗?

如何在 SwiftUI 中将图像传递到 2 个视图

SwiftUI View Builder 参数无法更改状态

P384 公钥获取IncorrectParameterSize

在 Swift 5.5 中编写同步和异步函数

Swift中switch 盒的详尽条件

快速覆盖属性

playground 导入:没有这样的模块Foo

如何在 Swift 中将 NSURL 转换为字符串