Steve Kuo Steve Kuo - 2 months ago 7
iOS Question

Swift concatenate two Ranges

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

Answer

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

Comments