You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何让SearchBar实现首字符匹配而非全字符搜索?

实现Swift搜索栏仅匹配开头字符的解决方案

当前代码的问题在于使用range(of:options:)时未指定锚定规则,导致只要字符串包含搜索内容就会被匹配(比如输入“Co”会同时命中Conejo和Sacoja)。要实现仅匹配开头字符的需求,可通过以下两种方式修改:


方式一:修改range(of:)的匹配选项

给range(of:)的options参数添加.anchored选项,强制匹配仅从字符串起始位置开始,同时修正代码中$0.text的笔误(数组元素本身是String类型,无需.text属性):

listEmployed = ["Conejo","Tetera","Aviteon","Sacoja"]
    
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    isSearching = true
    arrayFilterEmployed = listEmployed
    if !searchText.isEmpty {
        let lowercasedSearchText = searchText.lowercased()
        arrayFilterEmployed = listEmployed.filter {
            $0.lowercased().range(of: lowercasedSearchText, options: [.caseInsensitive, .anchored]) != nil
        }
    }
    
    if arrayFilterEmployed?.count == 0 {
        searchBar.showsCancelButton = false
        fountLabel?.isHidden = false
    } else {
        categoryTableView?.reloadData()
        fountLabel?.isHidden = true
    }
    categoryTableView?.reloadData()
}

方式二:使用hasPrefix方法(更简洁直观)

直接调用String的hasPrefix方法,结合大小写转换实现不区分大小写的前缀匹配:

listEmployed = ["Conejo","Tetera","Aviteon","Sacoja"]
    
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    isSearching = true
    arrayFilterEmployed = listEmployed
    if !searchText.isEmpty {
        let lowercasedSearchText = searchText.lowercased()
        arrayFilterEmployed = listEmployed.filter {
            $0.lowercased().hasPrefix(lowercasedSearchText)
        }
    }
    
    if arrayFilterEmployed?.count == 0 {
        searchBar.showsCancelButton = false
        fountLabel?.isHidden = false
    } else {
        categoryTableView?.reloadData()
        fountLabel?.isHidden = true
    }
    categoryTableView?.reloadData()
}

两种方式都能实现输入“Co”时仅返回Conejo的需求。

内容的提问来源于stack exchange,提问作者Mauriho Enrique Escurra Colqui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:22:49