例如,我有一个数组 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/