[英]How to remove dictionary[String:AnyObject] for array using filter function in swift?
[英]How to remove element in dictionary by using filter in iOS Swift
我有一个看起来像这样的字典,我想删除 *所有包含 stock = 0 的元素。
variations = {
"64FB5468-96E9-41A4-A779-3FB57FF1296B" = {
price = 10;
sku = 123456;
stock = 1;
volume = 1L;
};
"A5EDB714-3D39-42DA-9A5C-2392D39C3AEB" = {
price = 20;
sku = 254648;
stock = 0;
volume = 2L;
};
"BCA98B51-B058-4ABE-9010-54B080B819FB" = {
price = 30;
sku = 284964;
stock = 0;
volume = 3L;
};
};
我使用了下面的代码,但是,它在展开错误时返回 found nil 。 如何正确删除变体字典中库存为 0 的字典? kSTOCK 是字符串“stock”的常量
let filterAllItems = self.allItems.filter({(($0.variations as AnyObject)[$0] as! [String:Any])[kSTOCK] as! Int > 0})
假设allItems
是一个[String:Any]
字典,制作一个(可变) variations
的副本,过滤对象,删除找到的键的值并将字典重新分配给allItems
if var variations = allItems["variations"] as? [String:[String:Any]] {
let allItemsWithStock0 = variations.filter({($0.value["stock"] as? Int) == 0})
for (key, _) in allItemsWithStock0 {
variations.removeValue(forKey: key)
}
allItems["variations"] = variations
}
public extension Dictionary {
@inlinable public mutating func removeIf(condition: (Self.Element) -> Bool) {
for (key, _) in filter(condition) { removeValue(forKey: key) }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.