IntStream equivalence in Swift

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

IntStream equivalence in Swift

问题

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

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

我知道在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.

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

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 最短版本:

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

我在这里使用了 Swift 的 范围运算符 来替代 IntStream。

以下是该函数的测试:

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

以下是输出结果:

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

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

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

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

Here is a test for that function:

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

Here is the output:

  1. 1 through 5: [4.4, 1.1, 3.3, 7.7, 8.8]
  2. 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:

确定