简体   繁体   中英

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

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)
}

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)
    }
}

An Alternative would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM