【问题标题】:IntStream equivalence in SwiftSwift 中的 IntStream 等价性
【发布时间】:2020-12-16 02:54:51
【问题描述】:

我正在研究 Java 中的一些组件,想知道将以下 Java 代码 sn-p 转换为 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。我是否需要编写一些嵌套循环或任何更好的解决方案?谢谢。

【问题讨论】:

    标签: java swift5 code-conversion intstream


    【解决方案1】:

    我相信这是您的函数的最短 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, 1.1, 3.3, 7.7, 8.8]
    result: Optional(4.4)
    

    【讨论】:

      猜你喜欢
      • 2015-05-15
      • 2017-12-06
      • 2017-03-29
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 2014-07-23
      • 2014-11-23
      • 1970-01-01
      相关资源
      最近更新 更多