-1

I have an Array which I have defined

  var array: [Int] = Array(1...24)

I then add

   array.insert(9999, atIndex: 0)

I would like to do something like

  var array: [Int] = Array(9999...9999,1...24)

Is this possible ?

Ryan Heitner
  • 13,119
  • 6
  • 77
  • 119

3 Answers3

2

You could simply concatenate the arrays created from each range:

let array = Array(10 ... 14) + Array(1 ... 24)

Alternatively:

let array = [10 ... 14, 1 ... 4].flatMap { $0 }

which has the small advantage of not creating intermediate arrays (as you can see in the open source implementation https://github.com/apple/swift/blob/master/stdlib/public/core/SequenceAlgorithms.swift.gyb).

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

For an array of ranges you define the array as

let array: [Range<Int>] = [0...1, 5...100]

and so on and so forth.

hola
  • 3,150
  • 13
  • 21
1

As MartinR mentioned, you could simply concenate arrays using the + operator; and if this method is an answer for you, than this thread is a duplicate (see MartinR:s link), and should be closed.


If you explicitly wants to initialize an Int array using several ranges at once (see e.g. hola:s answer regarding array of ranges), you can make use of reduce as follows

let arr = [1...5, 11...15].reduce([]) { $0.0 + Array($0.1) }

Or, alternatively, flatten

var arr = Array([1...5, 11...15].flatten())

Both the above yields the following result

print(arr.dynamicType) // Array<Int>
print(arr)             // [1, 2, 3, 4, 5, 11, 12, 13, 14, 15]
Community
  • 1
  • 1
dfrib
  • 70,367
  • 12
  • 127
  • 192