如何过滤数据以开始而不是包含

How do I filter data to startswith instead of contains

我有一个 UITableView,它有一个搜索控制器,用于使用下面的代码过滤数据

func updateSearchResults(for searchController: UISearchController) {
     let searchString = searchController.searchBar.text
     filteredArray = data.filter({ (country) -> Bool in let countryText: NSString = country as NSString         
     return (countryText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound })
     suggestionview.reloadData()
}

如何才能使搜索通过查看字符串的开头而不是匹配任何地方来过滤 table。

例如,目前如果我在搜索输入中输入 Lon,我会得到包含 Lon 的所有内容的列表(在到达伦敦之前仍然是一个巨大的列表)。

你应该看看hasPrefix(_:)

Returns a Boolean value indicating whether the string begins with the specified prefix.

例如:

let items = [
    "London",
    "Londis",
    "Somelond",
    "Freelond"
]

let searchTerm = "Lon"

for item in items.filter({ itm -> Bool in
    itm.lowercased().hasPrefix(
        searchTerm.lowercased()
    )
}) {
    print(item)
}

// Output
London
Londis


或针对您的具体情况:

filteredArray = data.filter({ country -> Bool in        
    country.lowercased().hasPrefix(
        searchString!.lowercased()
    )
)

为什么使用NSString?更喜欢 Swift 中的 String 3+:

filteredArray = data.filter({ (country) -> Bool in 
    let countryText: NSString = country as NSString         
    return (countryText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound })
    

=>

filteredArray = data.filter({ country -> Bool in 
    return country.range(of: searchString!, options: .caseInsensitive) != nil })

您使用了 .caseInsenstive 选项,但还有 .anchored 您可能感兴趣的选项:

Search is limited to start (or end, if NSBackwardsSearch) of source string.

filteredArray = data.filter({ country -> Bool in 
    return country.range(of: searchString!, options: [.caseInsensitive, .anchored]) != nil })