问题
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