如果我的主阵列是["Hello","Bye","Halo"]
,并且我正在搜索"lo"
,它将仅过滤数组["Hello", "Halo"]
.
这就是我尝试过的:
let matchingTerms = filter(catalogNames) { $0.rangeOfString(self.txtField.text!, options: .CaseInsensitiveSearch) != nil }
它抛出
Type of expression is ambiguous without more context
有什么建议?
contains
改为使用:
let arr = ["Hello","Bye","Halo"] let filtered = arr.filter { $0.contains("lo") } print(filtered)
产量
["你好","光环"]
感谢@ user3441734指出该功能当然仅在您使用时可用 import Foundation
在Swift 3.0中
let terms = ["Hello","Bye","Halo"] var filterdTerms = [String]() func filterContentForSearchText(searchText: String) { filterdTerms = terms.filter { term in return term.lowercased().contains(searchText.lowercased()) } } filterContentForSearchText(searchText: "Lo") print(filterdTerms)
产量
["Hello", "Halo"]
斯威夫特3.1
let catalogNames = [ "Hats", "Coats", "Trousers" ] let searchCatalogName = "Hats" let filteredCatalogNames = catalogNames.filter { catalogName in return catalogName.localizedCaseInsensitiveContains(searchCatalogName) } print(filteredCatalogNames)