IntStream equivalence in Swift

huangapple go评论73阅读模式
英文:

IntStream equivalence in Swift

问题

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

public func doTest(items: [Double]) {
    // 我知道我应该检查items的数量。假设数量为10。
    let max = (1..<5).map { i in
        items[i] - items[i - 1]
    }.max() ?? 0.0
}

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

英文:

I am investigating some of the components in Java and wondering what is the best practice to convert the following Java code snippet to Swift.

public void doTest(ArrayList&lt;Double&gt; items) {
    // I know that I should check the count of items. Let&#39;s say the count is 10.
	double max = IntStream.range(1, 5)
					.mapToDouble(i -&gt; items.get(i) - items.get(i - 1))
					.max().getAsDouble();
}

AlI I know is there is no equivalent parallel aggregate operations in Swift to replicate the IntStream. Do I need to write some nested loops or any better solution? Thank you.

答案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 到 5:\(items[1...5])")
    let result = doTest(items: items)
    print("结果:\(String(describing: result))")
}

以下是输出结果:

1 到 5:[4.4, 1.1, 3.3, 7.7, 8.8]
结果:Optional(4.4)
英文:

I believe this is the shortest Swift equivalent of your function:

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

I'm using a Swift Range Operator in place of an IntStream.

Here is a test for that function:

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

Here is the output:

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

huangapple
  • 本文由 发表于 2020年8月27日 16:42:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63612330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定