搜索多个单词,忽略Swift中的顺序

时间:2019-01-15 21:15:00

标签: arrays swift string search filter

我目前有一个UITextField,可以在其中输入搜索字符串,它将按特定顺序返回包含该文本的数组中的任何字符串。但是,我想使搜索每个单词而忽略数组中字符串的顺序成为可能。

var results = [String]()
let filterArray = ["Big green bubble", "Red bubble", "A bubble in green", "Small green bubble", "This bubble is green"]     
let textString = "green bubble" 
for i in 0 ..< filterArray.count { 
    let checkString = filterArray[i] 
    let filterRange = (checkString as NSString).range(of: textString, options: .caseInsensitive) 
    if filterRange.location != NSNotFound { 
        results.append(checkString) 
    }
}  
print(results) // returns ["Big green bubble", "Small green bubble"]

我希望它也包含“绿色气泡” “此气泡绿色” ,因为它包含了我要搜索的每个单词。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

只需过滤来自filterArray的包含这两个词的元素

let filterArray = ["Big green bubble", "Red bubble", "A bubble in green", "Small green bubble", "This bubble is green"]
let textString = "green bubble".lowercased()
let words = textString.components(separatedBy: " ")
let results = filterArray.map { $0.lowercased() }.filter { string in words.allSatisfy { string.components(separatedBy: " ").contains($0) } }

print(results) /* ["Big green bubble", "A bubble in green", "Small green bubble", "This bubble is green"] */

答案 1 :(得分:2)

您可以使用一个集合并检查相交计数是否等于查询中的单词数:

let filterArray = ["Big green bubble", "Red bubble", "A bubble in green", "Small green bubble", "This bubble is green"]
let textString = "green bubble"
let wordsSet = Set(textString.components(separatedBy: " "))
let queryResult = filterArray.filter {
    Set($0.components(separatedBy: " ")).intersection(wordsSet).count == wordsSet.count
}
queryResult  // "Big green bubble", "A bubble in green", "Small green bubble", "This bubble is green"]

如果您需要不区分大小写,则可以将所有单词都映射为小写:

let wordsSet = Set(textString.lowercased().components(separatedBy: " "))
let queryResult = filterArray
    .map { $0.lowercased() }
    .filter {
    Set($0.components(separatedBy: " "))
        .intersection(wordsSet).count == wordsSet.count
}