Reputation: 2341
I want to add an extension for Array
to replace elements by index set:
extension Array {
mutating func replace(newElements: [Element], at indexes: IndexSet) {
//implementation here
}
}
And an example of using:
var set: IndexSet = [2, 1]
var array = ["0", "1", "2", "3", "4"]
array.replace(newElements: ["@", "%"], at: set) // custom method from future extension
print(array) //Prints ["0", "%", "@", "3", "4"]
But I have trouble with getting element from IndexSet
by index. How I can do it? Or maybe you know more elegant solution for replacing elements in array. I'm using IndexSet
instead Array<Int>
because later I'll use it for replacing sections in UITableView
.
Upvotes: 0
Views: 131
Reputation: 6393
As @Alexander mentions above it makes little sense to use an IndexSet as this is not ordered. What you probably want is an array of Int
s for each index. That should leave you with something like this:
extension Array {
mutating func replace(newElements: [Element], at indexes: [Int]) {
for (index, position) in indexes.enumerated() {
guard position < count else {
// error handling
return
}
remove(at: position)
insert(newElements[index], at: position)
}
}
}
Upvotes: 0
Reputation: 9943
There's nothing wrong with using [Int]
instead of IndexSet
, when you use this, you have to use sth like indexes.index(indexes.startIndex, offsetBy: 1)
to access the index, very annoying, I advised just use [Int]
like other array function and throws error when the value is out of bounds
Upvotes: 1