过滤字符串数组,包括"喜欢"条件

Roi*_*lia 24 arrays string filter ios swift

如果我的主阵列是["Hello","Bye","Halo"],并且我正在搜索"lo",它将仅过滤数组["Hello", "Halo"].

这就是我尝试过的:

 let matchingTerms = filter(catalogNames) {
        $0.rangeOfString(self.txtField.text!, options: .CaseInsensitiveSearch) !=  nil
    }
Run Code Online (Sandbox Code Playgroud)

它抛出

Type of expression is ambiguous without more context
Run Code Online (Sandbox Code Playgroud)

有什么建议?

luk*_*302 69

contains改为使用:

let arr = ["Hello","Bye","Halo"]
let filtered = arr.filter { $0.contains("lo") }
print(filtered)
Run Code Online (Sandbox Code Playgroud)

产量

["你好","光环"]

感谢@ user3441734指出该功能当然仅在您使用时可用 import Foundation

  • .. 并且不要忘记 import Foundation (2认同)

Ash*_*k R 29

在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)
Run Code Online (Sandbox Code Playgroud)

产量

["Hello", "Halo"]
Run Code Online (Sandbox Code Playgroud)

  • 当某人只搜索过滤字符串数组时,他/她将获得答案以及可能更新升级版本中语法的知识 (7认同)
  • 我认为它被要求使用Swift 2,当时它是真实的,现在我们正在使用Swift 3,所以它在这一刻更有价值. (7认同)
  • @GhostCat因为像我这样的人来自谷歌寻找Swift 3解决方案:) (4认同)

小智 6

斯威夫特3.1

let catalogNames = [ "Hats", "Coats", "Trousers" ]
let searchCatalogName = "Hats"

let filteredCatalogNames = catalogNames.filter { catalogName in 
    return catalogName.localizedCaseInsensitiveContains(searchCatalogName)
}

print(filteredCatalogNames)
Run Code Online (Sandbox Code Playgroud)