I have two Ranges:
let r1: Range<Int> = 1...3
let r2: Range<Int> = 10...12
Is there a Swift way to concat/join the two ranges such that I can iterate over both of them in one for
loop?
for i in joined_r1_and_r2 {
print(i)
}
Where the results would be:
1
2
3
10
11
12
You could create a nested array and then join them.
// swift 3:
for i in [r1, r2].joined() {
print(i)
}
The result of joined()
here is a FlattenBidirectionalCollection
which means it won't allocate another array.
(If you are stuck with Swift 2, use .flatten()
instead of .joined()
.)
Here is one way to do it:
let r1 = 1...3
let r2 = 10...12
for i in Array(r1) + Array(r2) {
print(i)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With