快速过滤数组 [英] filtering array in swift

查看:67
本文介绍了快速过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过一个或多个标志过滤自定义对象的数组?

How can i filter an array of custom objects by one ore more flags ?

let flags = ["New product", "Season 2014", "Season 2015", "Product available"]

具有一个或多个静态标志很容易:

With one flag or more static flags is easy:

let filteredArray = myCustomObjectsArray.filter() { $0.isNew == true }

let filteredArray = myCustomObjectsArray.filter() { $0.isNew == true && $0.season.rangeOfString("14") && $0.season.rangeOfString("15") && $0.isAvailable }

但是如果标志是动态的,即标志数组是通过用户点击表视图的单元格来创建的呢?

But what if flags are dynamic i.e. flags array is created by user tapping on cells of the tableview ?

另一个问题是尝试在`filter(){condition1&& condition2等}. 表达是复杂的,要在合理的时间内解决……".

Other problem is an error when trying to concatenate multiple conditions in `filter() { condition1 && condition2 etc.}. " Expression was to complex to be solved in reasonable time ...".

因此,flags数组是用户选择的内容(仅是来自tableview单元格的标题).如果flags数组为["New product","Season 2015"],我想例如以.isNew和.season.rangeOfString("15")进行过滤.所以我按属性而不是按字符串排序.

So, flags array is what user selected (just titles from a tableview cells). If flags array is ["New product", "Season 2015"], i want to filter by .isNew and .season.rangeOfString("15") for example. So i'm sorting by properties and NOT by string.

推荐答案

您尚未发布所有必需的代码,.isNew.season来自何处?它似乎是自定义对象.

You have not posted all of the necessary code, where does .isNew and .season come from? It would appear to be custom objects.

您提到的错误(表达式太复杂而无法在合理的时间内解决")已经有了答案:

The error you refer to ("Expression was too complex to be solved in reasonable time") already has an answer:

如果条件失败且表达式过于复杂

话虽如此,您应该可以通过将表达式的每个部分分成单独的语句来解决此问题:

Having said that, you should be able to resolve this by separating out each part of the expression into separate statements:

let filteredArray = myCustomObjectsArray.filter() {
    let isNew = $0.isNew == true
    let is14 = $0.season.rangeOfString("14")
    let is15 = $0.season.rangeOfString("15")
    let isAvailable = $0.isAvailable
    return isNew && is14 && is15 && isAvailable
}

这篇关于快速过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆