Swift 4.2
I have multiple functions that replace an object or struct in an array if it exists, and if it does not exist, it adds it.
func updateFruit(_ fruit: Fruit)
{
if let idx = fruitArray.firstIndex(where: { $0.id == fruit.id })
{
fruitArray[idx] = fruit
}
else
{
fruitArray.append(fruit)
}
}
Obviously I could make this into extension on Array:
extension Array
{
mutating func replaceOrAppend(_ item: Element, whereFirstIndex predicate: (Element) -> Bool)
{
if let idx = self.firstIndex(where: predicate)
{
self[idx] = item
}
else
{
append(item)
}
}
}
However, is there a simpler, easier way of expressing this? Preferably using a closure or build-in function.
NOTE: current implementation does not allow using a set.
Fruit
conform toEquatable
. Doing so you don't need a predicate. If you would like to use aSet
just make it conform toHashable
as well.$0.id == newthing.id
, or do they have other predicates? Are all the predicates$0.<prop> == newthing.<prop>
(even if not justid
)? Or are these predicates much more complex? Generic code must always start from how it is called or you'll go down the wrong road.