英文:
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<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();
}
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]) -> 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("1 through 5: \(items[1...5])")
let result = doTest(items: items)
print("result: \(String(describing: result))")
}
Here is the output:
1 through 5: [4.4, 1.1, 3.3, 7.7, 8.8]
result: Optional(4.4)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论