arrays - 将多个索引处的项目插入数组

标签 arrays swift insert indices

例如,我有一个数组 arr = [1,2,3,4,5,6,7,8,9,10],我想在位置 0、5、8 和 9 处添加数字 12。

为了实现这个我尝试过

extension Array {
    mutating func remove(_ newElement: Element, at indexes: [Int]) {
        for index in indexes.sorted(by: >) {
            insert(_ newElement: Element, at: index)
        }
     }
  }

但随后我得到错误:在第 4 行中对成员 'insert(_:at:) 的引用不明确。有可能以这种方式做到这一点吗? 我使用 Xcode 9.2

最佳答案

您的插入函数当前未接收元素参数。您正在使用插入功能,而不是声明它。我还重命名了您的函数以进行使用说明。

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

extension Array {
    mutating func add(_ newElement: Element, at indices: [Int]) {
        for index in indices(by: >) {
            insert(newElement, at: index)
        }
    }
}

arr.add(12, at: [0, 5, 8, 9])
print(arr)

关于arrays - 将多个索引处的项目插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49261104/

相关文章:

javascript - 尽管使用了唯一键,但 v-for 在使用数组拼接时删除了错误的元素

swift - UICollectionViewCells 在重新排列后重置其大小

ios - Swift Firebase - 使用文档 UID 获取当前用户以填充列表

php - 在关系型 mysql 数据库中的多个表中执行多个插入查询的正确方法是什么?

php - MySQL 只插入两个字段

python - 如何在数组中查找数组的索引

arrays - 我如何从 Mongoose 的数组中找到对象

javascript - 如何在 JavaScript 中将两个数组转换为一个对象?

ios - 如何确定 Google map 图 block 是否已加载

SQL - 复制同一表但具有不同外键 ID 的行