Reputation: 973
So I wanted to insert the objects of an array into another array. Swift arrays seem to missing an equivalent method to - (void)insertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes
, but all is well 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]
All is well? Not quite! The following gives a compile-time error ("[Int] is not convertible to Int"):
var array = [0,4,5]
var array2 = [1,2,3]
array[1..<1] = array2
Is there a sane explanation for this?
Edit:
Ok, the following works (thanks Greg):
array[1..<1] = array2[0..<array2.count]
As well as this:
let slice = array2[0..<array2.count]
array[1..<1] = slice
But right now I'm utterly confused how this works. Gregs explanation that I was trying to insert array2
itself into array
makes sense, but I fail to see the difference to just using an array literal, as well as why it works with a slice (which seems to be an undocumented implementation detail?).
Upvotes: 3
Views: 1234
Reputation: 51911
Range subscription on Array<T>
works only with Slice<T>
.
subscript (subRange: Range<Int>) -> Slice<T>
In your case, array2
is not a Slice<Int>
. That's 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)
Moreover, assigning to range on Array
has some bugs I think. for example:
var array = [0,1,2,3,4,5]
array[1...5] = array[1...1]
The result array should be [0, 1]
but it actually remains to be [0,1,2,3,4,5]
. It only happens if the startIndex
of the range is the same, and the slice is constructed from the same array.
On the other hand, replaceRange()
works as expeceted:
var array = [0,1,2,3,4,5]
array.replaceRange(1...5, with: array[1...1])
// -> [0,1]
Upvotes: 3
Reputation: 25459
This is happening because you want to insert an array2 (Array) not elements from the array, try this:
array[1..<1] = array2[0..<array2.count]
Upvotes: 4