SwiftUI - Indexset to index in array
Here is possible approach (taking into account that in general offsets
can contain many indexes)
func removePeriods(at offsets: IndexSet) {
theperiodlist.periods =
theperiodlist.periods.enumerated().filter { (i, item) -> Bool in
let removed = offsets.contains(i)
if removed {
AdjustProfileRemove(period: item)
}
return !removed
}.map { $0.1 }
}
.onDelete is declared as
@inlinable public func onDelete(perform action: ((IndexSet) -> Void)?) -> some DynamicViewContent
IndexSet is simply Set of all indexes of the elements in the array to remove. Let try this example
var arr = ["A", "B", "C", "D", "E"]
let idxs = IndexSet([1, 3])
idxs.forEach { (i) in
arr.remove(at: i)
}
print(arr)
so the resulting arr is now
["A", "C", "D"]
The reason, why .onDelete use IndexSet is that more than one row in List could be selected for delete operation.
BE CAREFULL! see the resulting array! Actually removing elements one by one needs some logic ...
Let's try
var arr = ["A", "B", "C", "D", "E"]
let idxs = IndexSet([1, 3])
idxs.sorted(by: > ).forEach { (i) in
arr.remove(at: i)
}
print(arr)
it works now as you expected, is it? the result now is
["A", "C", "E"]
Based on
theperiodlist.periods.remove(atOffsets: offsets)
it seems, that the ThePeriodList
already has build-in function with required functionality.
in your case just replace
AdjustProfileRemove(period: theperiodlist.periods[XXX])
with
offsets.sorted(by: > ).forEach { (i) in
AdjustProfileRemove(period: theperiodlist.periods[i])
}