How does one search an array of dictionaries for a match and replace that match with another dictionary?
Where lineItemsArray:Array is an array of dictionaries, I am looking to search the array elements for a match, return the index of that match, and then replace the dictionary at that index with a new one. Each dictionary in the array contains a recordId key which will be used for the search. Each recordId is unique and the search will always return a single result.
The new data that will be replacing the matching record is generated by web service and returned as a dictionary. (see below)
Here are my specific questions:
This is a sample of what the lineItemsArray looks like:
[{
buyFromCompanyId = 1;
buyFromJobId = 5276;
comment = "";
componentId = 2331;
description = "";
fulfillmentStatus = 0;
globalJobId = 2470;
inventoryItemId = 1824;
isSerialized = 1;
itemClass = 0;
itemQty = 2;
lineItemId = 50853;
priceRecordId = 152693;
productName = "Bose L1 Compact";
qtyAlreadyPulled = 0;
qtyRate1 = 3;
qtyRate2 = "";
qtyTotalStock = "";
rate1 = "";
rate2 = "";
sellToCompanyId = 1;
}, {
buyFromCompanyId = 1;
buyFromJobId = 5276;
comment = "";
componentId = "";
description = "";
fulfillmentStatus = 0;
globalJobId = 2470;
inventoryItemId = 2010;
isSerialized = "";
itemClass = "";
itemQty = 2;
lineItemId = 50854;
priceRecordId = 152695;
productName = "C13 IEC Cable (Standard)";
qtyAlreadyPulled = 0;
qtyRate1 = "";
qtyRate2 = "";
qtyTotalStock = 23;
}, {
buyFromCompanyId = 1;
buyFromJobId = 5276;
comment = "";
componentId = "";
description = "";
fulfillmentStatus = 0;
globalJobId = 2470;
inventoryItemId = 2046;
isSerialized = 1;
itemClass = "";
itemQty = 2;
lineItemId = 50855;
priceRecordId = 152697;
productName = "L1 compact amp unit";
qtyAlreadyPulled = 0;
qtyRate1 = "";
qtyRate2 = "";
qtyTotalStock = 1;
}]
Unfortunately, Swift's global find method looks for a specific value instead of a value matching a predicate. You can define your own this way:
func find<C: CollectionType>(collection: C, predicate: (C.Generator.Element) -> Bool) -> C.Index? {
for index in collection.startIndex ..< collection.endIndex {
if predicate(collection[index]) {
return index
}
}
return nil
}
Then you can find the index of the dictionary in question and replace it directly:
let index = find(lineItemsArray) { $0["recordId"] == replaceKey }
if let index = index {
lineItemsArray[index] = newDictionary
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With