Swift combines two ranges

I have two ranges:

let r1: Range<Int> = 1...3
let r2: Range<Int> = 10...12

Is there a way to quickly move to combine the two ranges so that I can iterate over both in the same loop for?

for i in joined_r1_and_r2 {
    print(i)
}

If the results are as follows:

1
2
3
10
11
12
+4
source share
4 answers

You can create a nested array and join them.

// swift 3:
for i in [r1, r2].joined() {
    print(i)
}

The result joined()here is FlattenBidirectionalCollection, which means that it will not allocate another array.

(If you're stuck in Swift 2, use .flatten()instead .joined().)

+6
source

Here is one way to do this:

let r1 = 1...3
let r2 = 10...12

for i in Array(r1) + Array(r2) {
    print(i)
}
+2
source

, .

:

let r1: Range<Int> = 1...3
let r2: Range<Int> = 10...12

for i in ([r1, r2].joinWithSeparator([])) {
    print(i)
}

, , . flatten kennytm - .

Of course, you can also just iterate over nested ones for:

for r in [r1, r2] {
    for i in r {
        print(i)
    }
}
0
source

An alternative would be:

var combined = [Int]
combined.append(contentsOf: 1...3)
combined.append(contentsOf: 10...12)
0
source

Source: https://habr.com/ru/post/1648876/


All Articles