Filtering Arrays Containing Multiple Data Types in Swift3

亡梦爱人 提交于 2019-12-11 16:13:41

问题


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:


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


来源:https://stackoverflow.com/questions/45371517/filtering-arrays-containing-multiple-data-types-in-swift3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!