gpt4 book ai didi

swift - 如何按搜索词过滤短语数组

转载 作者:行者123 更新时间:2023-11-28 11:27:28 26 4
gpt4 key购买 nike

我有一个 UISearchBar,我正在按这样的搜索词过滤一个 UICollectionView:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

filteredRecipes = getRecipes().filter({( recipe : Recipe ) -> Bool in
return recipe.name.lowercased().contains(searchText.lowercased())
})

if searchText == "" || searchText == " " {
filteredRecipes = getRecipes()
}

}

每个 Recipe 都有一些属性,我想过滤的属性之一是 name,它由几个词组成,例如“Red Velvet Cake ”。现在,如果我从以下位置搜索任何内容,该函数将返回此食谱:

  • 红色
  • r
  • 绒布

我如何才能让它根据 name 中每个单词的 start 过滤食谱。所以它只会在我搜索时返回食谱:

  • 红色
  • 天鹅绒
  • 蛋糕
  • 天鹅绒蛋糕

如果搜索词什么都没有,或者只是空格,它还会返回所有食谱吗?

我在这里寻找答案,但只能找到与我现有的解决方案类似的解决方案。谢谢!

最佳答案

使用 filter(_:) 的组合, contains(where:) hasPrefix(_:) 像这样,

filteredRecipes = getRecipes().filter({
let components = $0.name.components(separatedBy: " ")
return components.contains(where: {
$0.lowercased().hasPrefix(searchText.lowercased())
})
})

关于swift - 如何按搜索词过滤短语数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57783326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com