3

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?).

1
  • 1
    Slice conforms to the ArrayLiteralConvertible protocol, that's why array[1..<1] = [1,2,3] works. But there is no automatic conversion from Array to Slice or vice versa. Commented Dec 9, 2014 at 10:42

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

Comments

3

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]

1 Comment

Thanks for the explanation and for showing me the correct method to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.