在Swift中将新元素插入数组 [英] Insert a new element into an array in Swift
问题描述
代码:
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"中插入新元素
I thank the newArray is a new mutable variable. So I get confuse. Why? I can't insert a new element into "newArray"
推荐答案
oldNums[1..<4]
is not an array, but an ArraySlice
:
类似Array的类型,代表任何Array,ContiguousArray或其他ArraySlice的子序列.
An Array-like type that represents a sub-sequence of any Array, ContiguousArray, or other ArraySlice.
数组切片的索引不是从零开始的,而是对应的 到原始数组的索引.这是一个改变 随Swift 2一起提供,并记录在
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:
为了保持一致性并更好地编写通用代码,ArraySlice 索引不再总是从零开始,而是直接映射到 他们正在切片的集合的索引并维护该映射 即使发生了突变.
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()
的无效索引,这就是为什么
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)
要创建真实"数组而不是切片,请使用Array()
构造函数:
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]
这篇关于在Swift中将新元素插入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!