Inserting an array into an array
So I wanted to insert array objects into another array. Swift arrays lack equivalent methods for - (void)insertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes
, but that's okay because we can use the following syntax:
var array = [0,4,5]
array[1..<1] = [1,2,3] // array = [0,1,2,3,4,5]
Things are good? Not really! The following is a compile-time error ("[Int] does not convert to Int"):
var array = [0,4,5]
var array2 = [1,2,3]
array[1..<1] = array2
Is there a reasonable explanation for this?
Edit:
Ok, the following works (thanks to Greg):
array[1..<1] = array2[0..<array2.count]
Besides:
let slice = array2[0..<array2.count]
array[1..<1] = slice
But right now I am completely confused how it works. The Gregs explanation I'm trying to insert array2
myself into array
makes sense, but I don't see any difference in just using the array literal, nor why it works with slice (which seems to be an undocumented implementation of the detail?).
source to share
Subscription Array<T>
only works with Slice<T>
.
subscript (subRange: Range<Int>) -> Slice<T>
In your case, array2
it is not Slice<Int>
. This is why you see the error.
Usually you should use replaceRange()
or splice()
, which works with arbitrary CollectionType
.
array.replaceRange(1..<1, with: array2)
// OR
array.splice(array2, atIndex: 1)
Also, Array
there are some bugs when assigning a range to I think. eg:
var array = [0,1,2,3,4,5]
array[1...5] = array[1...1]
There should be an array of results [0, 1]
, but it actually remains [0,1,2,3,4,5]
. This only happens if the startIndex
range is the same and the slice is built from the same array.
On the other hand, it replaceRange()
works like expeceted:
var array = [0,1,2,3,4,5]
array.replaceRange(1...5, with: array[1...1])
// -> [0,1]
source to share