Filtering Arrays Containing Multiple Data Types in

2019-08-16 17:34发布

I have an array like:-

var arrayData : Array<Dictionary<String, [BottleModel]>> = []

Bottle model :-

class BottleModel: NSObject {

    var name : String
    var price : Int
    var reviews : Int
    var category : String
    var quantity : String
    var id : String
    var shopData : ShopModel
}

I want filtered array where price is > 2000

I tried let searchByInts = arrayData.filter({m in m.price < 200}) but getting below error:

Contextual closure type '(Dictionary) -> Bool' expects 1 argument, but 0 were used in closure body

How to filter such kind of array based on price

1条回答
祖国的老花朵
2楼-- · 2019-08-16 18:15

Working code:

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]]] = []

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.

Alternative using flatMap:

let flat = arrayData.flatMap { $0.values.flatMap { $0 } }
let searchByInts2 = flat.filter { $0.price < 200 } // or some other criteria
查看更多
登录 后发表回答