首先,您已经定义了一个包含单个字符串的数组。
你可能想要的是
let itemsArray = ["Google", "Goodbye", "Go", "Hello"]
然后您可以使用 contains(array, predicate) 和 rangeOfString() - 可选地
.CaseInsensitiveSearch - 检查数组中的每个字符串
如果它包含搜索字符串:
let itemExists = contains(itemsArray) {
$0.rangeOfString(searchToSearch, options: .CaseInsensitiveSearch) != nil
}
println(itemExists) // true
或者,如果您想要一个包含匹配项的数组而不是是/否
结果:
let matchingTerms = filter(itemsArray) {
$0.rangeOfString(searchToSearch, options: .CaseInsensitiveSearch) != nil
}
println(matchingTerms) // [Google, Goodbye, Go]
Swift 3 更新:
let itemExists = itemsArray.contains(where: {
$0.range(of: searchToSearch, options: .caseInsensitive) != nil
})
print(itemExists)
let matchingTerms = itemsArray.filter({
$0.range(of: searchToSearch, options: .caseInsensitive) != nil
})
print(matchingTerms)