如何使用键值从字典数组中删除对象

5

我有一个类似下面的字典数组:

    {
        "photo_id" = 255025344921316;
        "photo_url" = "https://scontent.xx.fbcdn.net/v/t1.0-0/p320x320/16143181_255025344921316_6580634265541865230_n.jpg?oh=4f6359dbc63241c9dfab29c8cfc570ef&oe=598E85AE";
    },

        {
        "photo_id" = 255024861588031;
        "photo_url" = "https://scontent.xx.fbcdn.net/v/t1.0-0/p75x225/16106022_255024861588031_911227627582642933_n.jpg?oh=0bc3fb9df0ccac44c9bd03e8ee1a407d&oe=597A199C";
    },

        {
        "photo_id" = 255024731588044;
        "photo_url" = "https://scontent.xx.fbcdn.net/v/t1.0-0/p320x320/16113986_255024731588044_6834401222098779590_n.jpg?oh=68b39d59c803e30754fa6aaab5ea3017&oe=598A3425";
    }

现在我想删除一个具有“photo_id:255024731588044”的对象。 我该如何做呢?
3个回答

9
你可以使用.index(where:)方法获取要删除的字典的索引,该方法执行0(n)
let index = array.index(where: { dictionary in
  guard let value = dictionary["photo_id"] as? Int
    else { return false }      
  return value == 255024731588044
})

如果index值不是nil,您可以使用它来删除它:
if let index = index {
  array.remove(at: index)
}

在这里,您可以下载游乐场。

非常有帮助的答案。 - Nischal Hada

3
假设数组的类型为[[String:Any]],您可以在其上使用过滤器来删除特定值。尝试执行以下操作:
let newArray = array.filter({ (dictionary) -> Bool in
    if let value = dictionary["photo_id"] as? Int{
        return value != 255024731588044
    }
    return false
})

0

试试这个:

let searchedPhotoID = 255024731588044
guard let index = arrayOfDict.index(where: {
    guard let photoID = $0["photo_id"] as? Int else { return false }
    return photoID == searchedPhotoID
}) else {
    return // photoID not found - handle somehow
}
arrayOfDict.remove(at: index)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接