Reputation: 1847
The following code works great in that it finds if I have an element within a nested array. If such an element does not exist the code inserts it.
I'm struggling to find a way to remove an existing element if it already exists so I can then insert an updated version of it.
Perhaps there is even a better way to just update the existing element without removing it first?
if insertSolution.contains(where: { $0.resourceName == name }) {
//remove $0
//insert new resource
print("Already inserted. Update needed!")
} else {
insertSolution.append(solution);
print("New solution. Insert needed!");
}
Upvotes: 0
Views: 263
Reputation: 539835
You can determine the index of an existing element, and update that element if it exists, otherwise append:
if let idx = insertSolution.firstIndex(where: { $0.resourceName == name }) {
// Update existing element:
insertSolution[idx] = ...
} else {
// Append new element:
insertSolution.append(...);
}
Upvotes: 1