Reputation: 1429
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"
Upvotes: 1
Views: 194
Reputation: 540105
oldNums[1..<4]
is not an array, but an ArraySlice
:
An Array-like type that represents a sub-sequence of any Array, ContiguousArray, or other ArraySlice.
The indices of array slices are not zero-based, but correspond to the indices of the original array. This is a change that came with Swift 2 and is documented in the Xcode 7.0 Release notes:
For consistency and better composition of generic code, ArraySlice indices are no longer always zero-based but map directly onto the indices of the collection they are slicing and maintain that mapping even after mutations.
In your case:
let oldNums: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var newArray = oldNums[1..<4]
print(newArray.indices)
// 1..<4
So 0
is an invalid index for insert()
, and that's why
newArray.insert(99, atIndex: 0)
crashes. To insert an element at the beginning of the slice, you can use
newArray.insert(99, atIndex: newArray.startIndex)
To create a "real" array instead of a slice, use the Array()
constructor:
let oldNums: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var newArray = Array(oldNums[1..<4])
print(newArray.indices)
// 0..<3
newArray.insert(99, atIndex:0)
print(newArray)
// [99, 2, 3, 4]
Upvotes: 4