如何从第一个索引过滤字符串数组,然后包含char



我有一系列国家。我需要使用搜索文本进行搜索和更新数组,但是从初始字符匹配开始,并非字符串中的任何地方。

例如:如果我搜索它应该返回印度,印度尼西亚...而不是中国...

我创建了bleow方法,该方法会查看整个字符串而不是初始字符。

另外,我在此功能中没有任何范围,所以如何获得字符串范围?

func searchCountry(for string: String) {
        if !string.isEmpty {
            let filtered = countries?.filter {
                $0.name?.range(of: string,
                               options: .caseInsensitive) != nil
            }
            guard let filteredCountries = filtered else { return }
        }
    }

您也可以将其用于适当的输出

func searchCountry(for string: String?) {
        if let searchText = string {
            let filter = countries.filter({ $0.lowercased().hasPrefix(searchText.lowercased()) })
            print(filter)
        }
    }
 $0.name?.range(of: string,options: [.anchored, .caseInsensitive]) != nil

使用锚定搜索缩写。它从一开始就开始。

相关内容

最新更新