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

Swift实现数组字符串部分匹配且不区分大小写的书籍作者过滤

实现作者名的部分匹配+不区分大小写过滤

修改后的代码(两种可选实现)

方案一:转小写后匹配(简洁直观)

var filteredBooksByAuthor: [Book] {
    if searchTextAuthor.isEmpty {
        books
    } else {
        let lowercasedQuery = searchTextAuthor.lowercased()
        books.filter { book in
            book.authors.contains { author in
                author.lowercased().contains(lowercasedQuery)
            }
        }
    }
}

方案二:用range(of:options:)实现更严谨的匹配(支持忽略重音)

var filteredBooksByAuthor: [Book] {
    if searchTextAuthor.isEmpty {
        books
    } else {
        books.filter { book in
            book.authors.contains { author in
                author.range(of: searchTextAuthor, options: [.caseInsensitive, .diacriticInsensitive]) != nil
            }
        }
    }
}

改动说明

  • 原代码的contains(searchTextAuthor)仅支持完全字符串匹配,无法满足部分匹配需求。
  • 方案一通过将搜索关键词和作者名都转为小写,再判断作者名的小写版本是否包含搜索词的小写版本,实现了不区分大小写的部分匹配。
  • 方案二利用Swift的range(of:options:)方法,通过指定[.caseInsensitive, .diacriticInsensitive]选项,不仅忽略大小写,还能忽略重音符号(比如将José和jose视为匹配),适配更多语言场景。

内容的提问来源于stack exchange,提问作者user1233894

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:12:06