Steve Kuo
Steve Kuo

Reputation: 63094

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

Upvotes: 9

Views: 4219

Answers (4)

cacoroto
cacoroto

Reputation: 279

An Alternative would be:

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

Upvotes: 1

kennytm
kennytm

Reputation: 523314

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

Upvotes: 15

vacawama
vacawama

Reputation: 154603

Here is one way to do it:

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

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

Upvotes: 2

Sulthan
Sulthan

Reputation: 130102

You will have to convert them to another structure because ranges have to be continuous.

One possible way:

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

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

There are multiple ways to achieve the same, I have used the one that is easily scalable to more ranges. flatten in kennytm's answer is a better choice.

Of course, you can also simply iterate in a nested for:

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

Upvotes: 0

Related Questions