简体   繁体   English

Swift 通过搜索词数组过滤数组结构

[英]Swift filter a array struct by an array of search words

I have created an array struct to house my values used in a list.我创建了一个数组结构来存放我在列表中使用的值。 Now I want to be able to search this list and every time the user makes a blank space it should be viewed by the program as two different searchwords that should both be met.现在我希望能够搜索此列表,并且每次用户创建一个空格时,程序都应该将其视为两个不同的搜索词,这两个搜索词都应该满足。 I have successfully created a function to get the searchwords but I don't really get how to now filter my stuctArray by all the searchWords.我已经成功创建了一个 function 来获取搜索词,但我真的不知道如何通过所有搜索词过滤我的 stuctArray。

let searchWords = findAllSearchResutsRecursive(searchWord) //example ["A", "B", ,"C"]

let filteredArray = listArray.filter {
    for word in searchWords {
        $0.firstname!.capitalized.contains(word.capitalized) ||
        $0.lastname!.capitalized.contains(word.capitalized) ||
        $0.id!.capitalized.contains(word.capitalized) ||
        $0.city!.capitalized.contains(word.capitalized)
    }
}

To clarify, if the searchWords is ["A", "N"] and one of the participants (people in the list) has the firstname "Anna" but nothing else match the search I still want to show it.澄清一下,如果 searchWords 是 ["A", "N"] 并且参与者之一(列表中的人)的名字是“Anna”,但没有其他匹配搜索我仍然想显示它。

Alternatively is if it would be better to convert the SearchWords to a set and in that way somehow filter them all at the same time.或者,如果将SearchWords转换为一个集合并以某种方式同时过滤它们会更好。

This is errors I get:这是我得到的错误: 在此处输入图像描述

You could rewrite it like this:你可以这样重写它:

let searchWords = findAllSearchResutsRecursive(searchWord) //example ["A", "B", ,"C"]

let filteredArray = listArray.filter {
    var matchFound = false
    for word in searchWords {
        if (
          $0.firstname!.capitalized.contains(word.capitalized) ||
          $0.lastname!.capitalized.contains(word.capitalized) ||
          $0.id!.capitalized.contains(word.capitalized) ||
          $0.city!.capitalized.contains(word.capitalized)
        ) {
            matchFound = true
          }
    }
    return matchFound
}

The outer filter function needs to return a boolean value.外部过滤器 function 需要返回 boolean 值。 To not iterate over all remaining words if a match is found you could use:要在找到匹配项时不遍历所有剩余的单词,您可以使用:

let filteredArray = listArray.filter {
    var result = false
    for word in searchWords {
        
        // check if any property contains the word
        if $0.firstname!.capitalized.contains(word.capitalized) ||
        $0.lastname!.capitalized.contains(word.capitalized) ||
        $0.id!.capitalized.contains(word.capitalized) ||
            $0.city!.capitalized.contains(word.capitalized){
            // set the result and break the loop
            result = true
            break
        }
    }
    // return the result
    return result
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM