swift - 在 Swift 中向数组中插入一个新元素

标签 swift swift2

代码:

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

所以 0insert() 的无效索引, 这就是为什么

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/

相关文章:

ios - 从通用更改为仅适用于 iPhone 后,iPhone 应用程序无法在 iPad 上正常运行

swift - #selector 在 Swift 4 中不起作用?

swift - 在 Swift 中创建实例时是使用 var 还是 let?

Swift:如何处理 TableView 和方法更新 TableView 之间的同步

ios - 在任何 tableView 函数之外获取索引路径

objective-c - Swift 类不符合带有错误处理的 Objective-C 协议(protocol)

ios - 如何从今天(本地)获取接下来的 10 个日期

ios - UISlider 长按可在 UITableView 中移动它

iphone - 采用 Equatable 协议(protocol)进行具有嵌套 Enum 值的 Enum

ios - 在 iOS 上使用 Whatsapp url scheme 调用