Why? insert a new element into array and it always crash!

Code:

let oldNums: [Int] = [1, 2, 3, 4, 5 ,6 , 7, 8, 9, 10]

var newArray = oldNums[1..<4]

newArray.insert(99, atIndex: 0) // <-- crash here

newArray.insert(99, atIndex: 1) // <-- work very well


I thank the newArray is a new mutable variable. So I get confuse.

Why? I can't insert a new element into "newArray"

Accepted Reply

A small code will clarify some points:

let oldNums: [Int] = [1, 2, 3, 4, 5 ,6 , 7, 8, 9, 10]
var newArray = oldNums[1..<4]
print(newArray.dynamicType) //->ArraySlice<Int>
print(newArray.indices) //->1..<4

The `newArray` is not an Array and its `indices` is not 0..<3 .

Replies

Starting from version "I don't remember", swift slices maintain the original array indexes and the last reason to use they just vanished.

newArray = oldNums[a..<b] will contains elements from a to b-1 (inclusive), and not from 0 to b-a-1 (inclusive).

I know: it's crazy.


P.S. Sorry for my bad english.

A small code will clarify some points:

let oldNums: [Int] = [1, 2, 3, 4, 5 ,6 , 7, 8, 9, 10]
var newArray = oldNums[1..<4]
print(newArray.dynamicType) //->ArraySlice<Int>
print(newArray.indices) //->1..<4

The `newArray` is not an Array and its `indices` is not 0..<3 .

Thanks in advance

finally, I got it, It's not real an Array. It's an ArraySlice and It's not zero-based.

So, To insert an element at the beginning of the slice, I can use

newArray.insert(99, atIndex: newArray.startIndex)

I think this could help you .


var newArray = Array(oldNums[1..<4])