Swift中的IntStream等效项

问题描述

我正在研究Java中的某些组件,并想知道将以下Java代码片段转换为Swift的最佳实践是什么。

public void doTest(ArrayList<Double> items) {
    // I kNow that I should check the count of items. Let's say the count is 10.
    double max = IntStream.range(1,5)
                    .mapTodouble(i -> items.get(i) - items.get(i - 1))
                    .max().getAsDouble();
}

我知道在Swift中没有等效的并行聚合操作来复制IntStream。我是否需要编写一些嵌套循环或任何更好的解决方案?谢谢。

解决方法

我相信这是最短的 Swift 等效函数:

func doTest(items: [Double]) -> Double? {
    return (1...5)
        .map { i in items[i] - items[i - 1] }
        .max()
}

我使用 Swift Range Operator 代替 IntStream。

这是对该函数的测试:

func testDoTest() throws {
    let items = [2.2,4.4,1.1,3.3,7.7,8.8,5.5,9.9,6.6]
    print("1 through 5: \(items[1...5])")
    let result = doTest(items: items)
    print("result: \(String(describing: result))")
}

输出如下:

1 through 5: [4.4,8.8]
result: Optional(4.4)