将多个索引处的项插入到数组中

时间:2018-03-13 16:21:51

标签: 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行插入(_:at :)。有可能以这种方式做到这一点吗? 我使用Xcode 9.2

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

extension Array  {

    mutating func add(_ newElement: Element, at indexes: [Int]) {

        for index in indexes {
            insert(newElement, at: index)
        }
    }
}

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

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

print(array) // [12, 1, 2, 3, 4, 12, 5, 6, 12, 12, 7, 8, 9, 10]

答案 1 :(得分:0)

尝试这样的事情:

extension Array{
    mutating func replaceElements(atPositions: [Int], withElement: Element){
        for item in atPositions{
            self.remove(at: item)
            self.insert(withElement, at: item)
        }
    }
}

请注意,您不一定需要使用self关键字;它仅用于清晰度。

答案 2 :(得分:0)

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

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

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

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