问题描述
我有一个类似的数组:-
I have an array like:-
var arrayData : Array<Dictionary<String, [BottleModel]>> = []
瓶子模型:-
class BottleModel: NSObject {
var name : String
var price : Int
var reviews : Int
var category : String
var quantity : String
var id : String
var shopData : ShopModel
}
我要过滤价格> 2000的数组
I want filtered array where price is > 2000
我尝试了 let searchByInts = arrayData.filter({m在m.price< 200}中)
但出现以下错误:
I tried let searchByInts = arrayData.filter({m in m.price < 200})
but getting below error:
如何根据价格过滤此类数组
How to filter such kind of array based on price
推荐答案
工作代码:
let searchByInts = arrayData.filter { $0.values.contains { $0.contains { $0.price > 2000 } } }
请使用文字写以下内容:
By the way please write the following using literals:
var arrayData : [[String : [BottleModel]]] = []
仍然不知道那是否是您真正想要的,因为您的目标非常不清楚。您有一个由数组组成的字典数组,实际上包含要过滤掉的值。如果 一个 BottleModel
的价格超过2000,您是否要保留其中包含的整个数组以及该数组所在的字典?您可能想要在过滤之前或之后将整个数据映射到一个平面数组中。
Still no idea if that is what you actually want because your goal is very unclear. You have an array of dictionaries of arrays which actually contain the values you want to filter out. If a BottleModel
costs more than 2000 do you want to keep the entire array it is contained in and the dictionary that array is in? You might want to map the entire data into one flat array before or after filtering.
使用 flatMap
的替代方法:
let flat = arrayData.flatMap { $0.values.flatMap { $0 } }
let searchByInts2 = flat.filter { $0.price < 200 } // or some other criteria
这篇关于在Swift3中过滤包含多种数据类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!