'insert item at multiple indices into an array
For example I have an array arr = [1,2,3,4,5,6,7,8,9,10] and I want to add the number 12 at position 0, 5, 8 and 9.
To achieve this I tried
extension Array {
mutating func remove(_ newElement: Element, at indexes: [Int]) {
for index in indexes.sorted(by: >) {
insert(_ newElement: Element, at: index)
}
}
}
But then I get the error: Ambiguous reference to member 'insert(_:at:) in the 4th line. Is it possible to do this in this way ? I use Xcode 9.2
Solution 1:[1]
Your insert function is not currently receiving an element argument. You are using the insert function, not declaring it. I also renamed your function for use clarification.
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)
Solution 2:[2]
Try something like this:
extension Array{
mutating func replaceElements(atPositions: [Int], withElement: Element){
for item in atPositions{
self.remove(at: item)
self.insert(withElement, at: item)
}
}
}
Please note that your don't necessarily need to use the self keyword; it was only used for clarity.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DeyaEldeen |
| Solution 2 | Silicon Unicorn |
