在Swift字典数组中查找并替换值

时间:2014-12-20 23:07:02

标签: arrays swift dictionary

如何搜索匹配的字典数组并将该匹配替换为另一个字典?

其中lineItemsArray:Array是一个字典数组,我希望在数组元素中搜索匹配项,返回该匹配项的索引,然后用新的字典替换该索引处的字典。数组中的每个字典都包含一个recordId键,用于搜索。每个recordId都是唯一的,搜索将始终返回单个结果。

将替换匹配记录的新数据由Web服务生成并作为字典返回。 (见下文)

以下是我的具体问题:

  • 如何搜索字典数组以进行匹配?
  • 如何返回该匹配的索引路径?
  • 在匹配索引处替换字典的最有效方式是什么?

这是lineItemsArray的样子:

[{
    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;
}]

2 个答案:

答案 0 :(得分:8)

不幸的是,Swift的全局find方法查找特定值而不是匹配谓词的值。您可以这样定义自己的方式:

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
}

然后你可以找到有问题的字典的索引并直接替换它:

let index = find(lineItemsArray) { $0["recordId"] == replaceKey }
if let index = index {
    lineItemsArray[index] = newDictionary
}

答案 1 :(得分:2)

您可以使用地图方法:

let newItems = map(lineItems, { originalDict in
    if originalDict["recordId"] == replaceId {
         return newDict
    }
    else {
        return originalDict
    }
})

或者作为较短的版本:

let newItems = map(lineItems) { $0["recordId"] == replaceId ? newDictionary : $0 }

map允许您将一个数组转换为另一个数组。在这里,我使用它将原始数组映射到一个新数组,其中只有具有匹配ID的元素被替换为新字典。

为此,我将一个闭包传递给map函数,该函数检查给定元素是否具有应该被替换的id。然后我使用三元运算符返回newDictionary或原始字典($ 0)。

我使用了两个虚构的变量:

  • newDict :您要用
  • 替换旧字典的字典
  • replaceId :您要替换的词典的ID

请注意,这会创建包含更新的原始数组的副本,而不是更新现有数组。