What's the easiest/right way to update an item in an array? I want the caller to have the updated array as well. So:
static func updateItem(updatedItem: Item, inout items: [Item]) -> Bool {
var item = items.filter{ $0.id == updatedItem.id }.first
if item != nil {
item = updatedItem
return true
}
return false
}
I want the caller to have the updated items (with the updated item). I think the problem with the above code is that it only updates the local variable item. What's the best way to actually update the relevant item inside the items array?
You do it the same way Superman gets into his tights — one leg at a time. Cycle through the incoming
inout
array and replace any items where theid
matches:Note that this is Swift 3 syntax where
inout
precedes the type, not the label.You can write it a little more "Swiftily" by using
map
:... but that amounts to the same thing in the end.