本文介绍了如何从匹配String的元组数组中获取所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似

var contactsname = [(String,String)]()//firstname,lastname

example = [[(alex,joe),(catty,drling),(alex,fox),(asta,alex)]

example = [(alex,joe),(catty,drling),(alex,fox),(asta,alex)]

我需要搜索与名字或姓氏匹配的元素,并返回与键匹配的所有元素

i need to search elements which are matching the firstname or lastname and return those all elements matching the key

func searchElementsForkey(key:String)->[(string,String)]{ //code here }

searchElementsForKey("alex")= [((alex,joe),(alex,fox),(asta,alex)]

searchElementsForKey("alex") = [(alex,joe),(alex,fox),(asta,alex)]

推荐答案

您可以像这样

var contactsname = [(String,String)]()//firstname,lastname
contactsname = [("alex","joe"),("catty","drling"),("alex","fox"),("asta","alex")]
let key = "alex"

如果您要使搜索名称与名字或姓氏完全匹配

If you want to exact match the search name either with First name or Last name

let filterArray = contactsname.filter { $0.0 == key || $0.1 == key }

如果要检查名字和姓氏包含特定的字符串,可以使用包含

If you want to check First name and Last name contains specific string for that you can use contains

let filterArray = contactsname.filter { $0.0.contains(key) || $0.1.contains(key) }

这篇关于如何从匹配String的元组数组中获取所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 20:08