Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift concatenate two Ranges

Tags:

ios

swift

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
like image 880
Steve Kuo Avatar asked Jul 23 '16 16:07

Steve Kuo


2 Answers

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().)

like image 191
kennytm Avatar answered Oct 02 '22 16:10

kennytm


Here is one way to do it:

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

for i in Array(r1) + Array(r2) {
    print(i)
}
like image 30
vacawama Avatar answered Oct 02 '22 17:10

vacawama