我有一个像
这样的元组数组var contactsname = [(String,String)]()//firstname,lastname
example = [(alex,joe),(catty,drling),(alex,fox),(asta,alex)]
我需要搜索与firstname或lastname匹配的元素,并返回与键匹配的所有元素
func searchElementsForkey(key:String)->[(string,String)]{ //code here }
searchElementsForKey(“alex”)= [(alex,joe),(alex,fox),(asta,alex)]
答案 0 :(得分:3)
你可以这样。
var contactsname = [(String,String)]()//firstname,lastname
contactsname = [("alex","joe"),("catty","drling"),("alex","fox"),("asta","alex")]
let key = "alex"
如果您想使用名字或姓氏与搜索名称完全匹配
let filterArray = contactsname.filter { $0.0 = key || $0.1 == key }
如果要查看名字和姓氏包含特定字符串,可以使用contains
let filterArray = contactsname.filter { $0.0.contains(key) || $0.1.contains(key) }