代码:
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
感谢 newArray 是一个新的可变变量。所以我很困惑。 为什么?我无法将新元素插入“newArray”
最佳答案
oldNums[1..<4]
不是一个数组,而是一个 ArraySlice
:
An Array-like type that represents a sub-sequence of any Array, ContiguousArray, or other ArraySlice.
数组切片的索引不是从零开始的,而是对应的 到原始数组的索引。这是一个改变 Swift 2 附带并记录在 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.
在你的情况下:
let oldNums: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var newArray = oldNums[1..<4]
print(newArray.indices)
// 1..<4
所以 0
是 insert()
的无效索引, 这就是为什么
newArray.insert(99, atIndex: 0)
崩溃。要在切片的开头插入一个元素,您 可以用
newArray.insert(99, atIndex: newArray.startIndex)
要创建“真正的”数组而不是切片,请使用 Array()
构造函数:
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]
关于swift - 在 Swift 中向数组中插入一个新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34151581/