[英]Filtering by checking if list contains elements of other list. How to do that?
I can't figure out how to correctly create the first return
. 我不知道如何正确创建第一个return
。 It would work like this but the problem is searchtestarrayone
always has a different length and it can be pretty large. 它将像这样工作,但问题是searchtestarrayone
始终具有不同的长度,并且可能会很大。 Started my journey with Swift a few weeks ago, so there might be stupid things in the code below and the answer can be obvious, forgive me. 几周前从Swift开始我的旅程,所以下面的代码中可能有一些愚蠢的事情,答案很明显,请原谅。
func updateSearchResults(for searchController: UISearchController){
if let searchText = searchController.searchBar.text, !searchText.isEmpty {
transformSearchResult()
filteredBusStopsArray = busStopsArray.filter { (busstop : BusStop) in
if !searchtestarrayone.isEmpty{
return busstop.stopName.lowercased().contains(searchtestarrayone[0]) || busstop.stopName.lowercased().contains(searchtestarrayone[1])
}
else{
return busstop.stopName.lowercased().contains(searchText.lowercased())
}
Looking for some tips. 寻找一些技巧。 Best regards. 最好的祝福。
You should map busStopsArray
to only include lowercased stop names and filter it with searchtestarrayone
. 您应该将busStopsArray
映射为仅包含小写的站点名称,并使用searchtestarrayone
对其进行过滤。
filteredBusStopsArray = (busStopsArray.map { $0.stopName.lowercased() }).filter {
searchtestarrayone.contains($0)
}
If you want to return whether busstop.stopName
contains any of the values of searchtestarrayone
's values, you can use contains.where
. 如果要返回busstop.stopName
是否包含searchtestarrayone
的任何值,则可以使用contains.where
。
if !searchtestarrayone.isEmpty{
return searchTestArrayOne.contains(where: {busStop.stopName.lowercased().contains($0)})
}
This will return true if any of the elements of searchTestArrayOne
are contained in busStop.stopName
and false otherwise. 如果任何元素这将返回true searchTestArrayOne
包含在busStop.stopName
否则为false。 contains(where:)
also exits early, as soon as it finds the first element matching the closure, so he full search array is only iterated through if there is no match. 当找到第一个与闭包匹配的元素时, contains(where:)
也会提前退出,因此只有在没有匹配项的情况下,才迭代整个搜索数组。
Please also make sure that you conform to the Swift naming convention, which is lower-camelCase for function and variable names. 还请确保您遵守Swift命名约定,即函数名和变量名的首字母为camelCase。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.