black_pearl
black_pearl

Reputation: 2699

How to combine two ClosedRange in Swift?

I am learning Quick Sort in swift and need to compose a complicated array.

Here is the code:

var arrayOne = 1...500
var arrayTwo = 501...1000
var array_one = arrayOne.reversed()
var array_two = arrayTwo.reversed()
var array = arrayOne + arrayTwo

I want to combine arrayOne + arrayTwo to array.

I can not use the + operator, Xcode tips me

Binary operator '+' cannot be applied to two 'CountableClosedRange' operands

I know how to get it by using for loops.

Elegant way is really needed. Such as Higher order function.

Upvotes: 1

Views: 1060

Answers (1)

Martin R
Martin R

Reputation: 539795

1...500 is a range and (1...500).reversed() is a collection. Both are sequences so that you can append them to an array:

let rangeOne = 1...500
let rangeTwo = 501...1000

let array = [] + rangeOne.reversed() + rangeTwo.reversed()

// [500, 499, ..., 2, 1, 1000, 999, ..., 502, 501]

Alternative solutions are:

let array = Array(rangeOne.reversed()) + rangeTwo.reversed()
let array = Array([rangeOne.reversed(), rangeTwo.reversed()].joined())
let array = Array(rangeOne.reversed()) + Array(rangeTwo.reversed())
let array = [rangeOne.reversed(), rangeTwo.reversed()].flatMap { $0 }

Upvotes: 2

Related Questions