如何确定各种字符串中是否包含2个或更多单词

时间:2018-03-05 02:32:10

标签: ios swift string

我的情况是一个值包含多个字段,并提供一个搜索栏,用户可以在其中输入可以在这些字段之间拆分的短语。

以下是来自游乐场的简短样本,说明了我想要完成的任务。

import Foundation

struct Item {
    let name: String
    let size: String
}
let itemA = Item(name: "stuff", size: "Large")
let itemB = Item(name: "something", size: "X-Large")
let items = [itemA, itemB]

let singleSearch = "stuff"
let singleFound = items.filter { $0.name.localizedStandardContains(singleSearch) ||
    $0.size.localizedStandardContains(singleSearch)
}
print(singleFound) // ItemA

let multiSearch = "stuff large"
let multiFound = items.filter { $0.name.localizedStandardContains(multiSearch) ||
    $0.size.localizedStandardContains(multiSearch)
}

print(multiFound) // Nothing found, expect to see itemA

此外,它必须能够在用户搜索时处理部分单词,以支持缩小可见选项。

let partialSearch = "stuff l"
let partialFound = items.filter { $0.name.localizedStandardContains(partialSearch) ||
    $0.size.localizedStandardContains(partialSearch)
}

print(partialFound) // Nothing found, expect to see itemA

我怀疑我可能需要将搜索词分成一个数组并单独处理每个单词,并查看组合检查的结果。我担心的是实际实现的领域要多得多,所以这可能是不切实际的。

1 个答案:

答案 0 :(得分:1)

作为一种快速解决方案,您可以执行以下操作:

let multiSearch = "st la"
let trimmed = multiSearch.trimmingCharacters(in: .whitespacesAndNewlines)
let multiSearchComponents = trimmed.components(separatedBy: " ")

var filtered = items
multiSearchComponents.forEach { searchTerm in
    filtered = filtered.filter { item in
        item.name.localizedStandardContains(searchTerm) || item.size.localizedStandardContains(searchTerm)
    }
}

print(filtered) //Prints itemA