thus
thus

Reputation: 1558

IntStream equivalence in Swift

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.

Upvotes: 2

Views: 240

Answers (1)

Ethan
Ethan

Reputation: 106

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)

Upvotes: 1

Related Questions