我正在尝试使用swift过滤数组,当我只是尝试过滤一些内容时它会很有效但是当我添加到列表中时我得到了这个错误:
表达太复杂,无法在合理的时间内解决;考虑 将表达式分解为不同的子表达式
以下是包含上述错误的代码:
filteredArray = workArray.filter { $0.stateName.localizedCaseInsensitiveContainsString(searchString!) || $0.firstName.localizedCaseInsensitiveContainsString(searchString!) || $0.lastName.localizedCaseInsensitiveContainsString(searchString!) || $0.countyName.localizedCaseInsensitiveContainsString(searchString!) || $0.cityName.localizedCaseInsensitiveContainsString(searchString!) || $0.communityName.localizedCaseInsensitiveContainsString(searchString!) || $0.sectionName.localizedCaseInsensitiveContainsString(searchString!) || $0.notes.localizedCaseInsensitiveContainsString(searchString!) || $0.email1.localizedCaseInsensitiveContainsString(searchString!) || $0.email2.localizedCaseInsensitiveContainsString(searchString!) || $0.email3.localizedCaseInsensitiveContainsString(searchString!) || $0.title.localizedCaseInsensitiveContainsString(searchString!) || $0.jobsiteID.localizedCaseInsensitiveContainsString(searchString!)}
我试图将此过程分开,就像这样
filteredArray = workArray.filter { $0.stateName.localizedCaseInsensitiveContainsString(searchString!) || $0.firstName.localizedCaseInsensitiveContainsString(searchString!) || $0.lastName.localizedCaseInsensitiveContainsString(searchString!) || $0.countyName.localizedCaseInsensitiveContainsString(searchString!) || $0.cityName.localizedCaseInsensitiveContainsString(searchString!) || $0.communityName.localizedCaseInsensitiveContainsString(searchString!) || $0.sectionName.localizedCaseInsensitiveContainsString(searchString!) || $0.notes.localizedCaseInsensitiveContainsString(searchString!) || $0.email1.localizedCaseInsensitiveContainsString(searchString!)}
和
filteredArray.appendContentsOf(workArray.filter { $0.email2.localizedCaseInsensitiveContainsString(searchString!) || $0.email3.localizedCaseInsensitiveContainsString(searchString!) || $0.title.localizedCaseInsensitiveContainsString(searchString!) || $0.jobsiteID.localizedCaseInsensitiveContainsString(searchString!)})
但是我在数组中获得了重复的对象。
我可以写一些其他的东西,然后寻找和删除重复的对象,但我宁愿不。我的问题是我应该如何过滤所有这些项目。
感谢您的所有帮助
答案 0 :(得分:3)
将表达式的巨大因素归结为数据类型的方法。
extension MyDataThingy {
func anyFieldContains(searchTerm term: String) -> Bool {
let fieldValues = [self.stateName, self.firstName, /* etc. */]
for value in fieldValues {
if value.localizedCaseInsensitiveContainsString(term) {
return true
}
}
return false
}
}
然后:
filteredArray = workArray.filter { $0.anyFieldContains(searchTerm: searchTerm) }
这将修复类型推理引擎的超时错误。它更具可读性,更易理解,更易于维护。
答案 1 :(得分:0)
尝试扩展语法
// return value
template <class T>
T Sum (T a, T b)
{
T result;
result = a + b;
return result;
}
// return as a pointer
template <class T>
T* Sum (T a, T b)
{
T result = new T();
*result = a + b;
return result;
}
这样你就可以帮助编译器理解闭包接收数组类型的元素并返回一个Bool值。