arrays - 如何从匹配字符串的元组数组中获取所有元素?

标签 arrays swift tuples

我有一个类似元组的数组

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

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

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

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

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"

如果你想用 First name 或 Last name 精确匹配搜索名称

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

如果你想检查 First name 和 Last name 是否包含特定的字符串,你可以使用 contains

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

关于arrays - 如何从匹配字符串的元组数组中获取所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43935024/

相关文章:

java - 在Java中不使用Set合并两个未排序的整数数组

java - 当您在不指定对象类型的情况下创建 ArrayList 时,它会在您添加第一个对象时自动创建它吗?

ios - UIToolbar 在带有 UIPickerView 的自定义 UITableViewCell 中没有响应

arrays - 数组或字典扩展中的 Swift 3.0 : compiler error when calling global func min<T>(T, T)

c++ - 将变体数组转换为 std::tuple

arrays - 迭代两个数组以在 Ruby 中生成哈希

javascript - 从数组中提取的列表中缺少值

swift - 如何从 Swift 中的字符串中删除单引号?

ios - 字典中的不同值(也称为元组)

Python:无法将 5 个列表的元组打印到文件