arrays - 搜索值数组以在字典中查找键

标签 arrays swift dictionary

我有一个字典,例如:

let dict = ["1" : ["one","une"],
            "2" : ["two","duex"]]

我正在使用以下代码来搜索值以获取 key 。例如,如果我搜索“one”,我将返回“1”。

let searchIndex = dict.firstIndex(where: { $0.value.contains("one") })

if let index = searchIndex {
  print("Return: \(dict[index].key)") // prints "1"    
} else {
  print("Could not find")
}

但是,这仅在我搜索完全匹配的字符串时有效。我如何才能仅通过搜索字符串的一部分来返回匹配的键。换句话说,如果我搜索“on”,它不会返回“1”。

最佳答案

你可以这样做:

let dict = ["1" : ["one","une"],
            "2" : ["two","deux"],
            "11": ["eleven, onze"]]

let searchText = "on"

let goodKeys = dict.keys.filter { key in
    dict[key]!.contains { word in
        return word.contains(searchText)
    }
}

print(goodKeys)     //["1", "11"]

在回答您的评论时,这里有一个解决方案:

let searchText = "one une"
let components = searchText.components(separatedBy: " ")

let goodKeys = dict.keys.filter { key in
    dict[key]!.contains { word in
        return components.contains { component in
            word.contains(component)
        }
    }
}

print(goodKeys)     //["1"] 

关于arrays - 搜索值数组以在字典中查找键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56551580/

相关文章:

swift - 核心数据 : How to Create a Persistent Document with Singleton Entity?

ios - 等待其他进程

swift - UICollectionView 动态单元格高度(Pinterest 布局)

java - 用数字替换符号

python:如何修改DataFrame中的字典?

Android AES/GCM/NoPadding 特定长度输入字节的错误?

java - 打印数组中设定值之间的所有数字

c# - 将项目添加到 string[] 数组

c - 结构中的可变长度数组

java - List.set 替换 TreeMap 中的所有索引