2

我正在研究 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。我是否需要编写一些嵌套循环或任何更好的解决方案?谢谢你。

4

1 回答 1

1

我相信这是您功能的最短 Swift 等效项:

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

我正在使用 Swift范围运算符代替 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, 1.1, 3.3, 7.7, 8.8]
result: Optional(4.4)
于 2021-05-03T18:14:20.750 回答