Akash Shindhe
Akash Shindhe

Reputation: 578

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

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

Upvotes: 1

Views: 1366

Answers (1)

Nirav D
Nirav D

Reputation: 72410

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

Upvotes: 4

Related Questions