How to get all the elements from array of tuples matching String?

我的梦境 提交于 2020-02-05 06:59:06

问题


i have a array of tuple like

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

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)]


回答1:


You can go like this.

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) }


来源:https://stackoverflow.com/questions/43935024/how-to-get-all-the-elements-from-array-of-tuples-matching-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!