在swift词典中找到一个包含字符串的键

Ade*_*ine 8 dictionary swift

我有一[String:String]本字典.我想获得与包含字符串"S"的任何键相关联的值.订单无关紧要.

这很简单:只需获取所有键,迭代,返回第一个匹配条件.

但是,我想用一种快速优雅的方法来做到这一点.使用a filtermap函数的东西.这就是我迷路的地方......

Mar*_*n R 11

由于您只对任何匹配值感兴趣,因此可以使用该indexOf()方法查找第一个匹配的字典条目.这是有效的,因为字典是键/值对的集合.

斯威夫特2:

let dict = ["foo": "bar", "PQRS": "baz"]
let searchTerm = "S"

if let index = dict.indexOf({ (key, _) in key.containsString(searchTerm) }) {
    let value = dict[index].1
    print(value)
} else {
    print("no match")
}
Run Code Online (Sandbox Code Playgroud)

一旦找到匹配的键,谓词就会返回true 并且枚举停止.这index是一个"字典索引",可以直接用于获取相应的字典条目.

对于不区分大小写的键搜索,请替换谓词

{
    (key, _) in  key.rangeOfString(searchTerm, options: .CaseInsensitiveSearch) != nil
}
Run Code Online (Sandbox Code Playgroud)

Swift 3中,您可以使用first(where:)查找第一个匹配元素,这样可以保存一个字典查找:

if let entry = dict.first(where: { (key, _) in key.contains(searchTerm) }) {
    print(entry.value)
} else {
    print("no match")
}
Run Code Online (Sandbox Code Playgroud)

对于不区分大小写的键搜索,请替换谓词

{
    (key, _) in key.range(of: searchTerm, options: .caseInsensitive) != nil
}
Run Code Online (Sandbox Code Playgroud)


vac*_*ama 6

你可以用flatMapcontainsString:

Swift 2.x:

let dict = ["one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6"]

let results = dict.flatMap { (key, value) in key.lowercaseString.containsString("o") ? value : nil }

print(results)
Run Code Online (Sandbox Code Playgroud)

输出:

["4", "1", "2"]
Run Code Online (Sandbox Code Playgroud)
print(results.first ?? "Not found")
Run Code Online (Sandbox Code Playgroud)
4
Run Code Online (Sandbox Code Playgroud)

或者,如果你喜欢神秘的一个衬垫:

let first = dict.flatMap { $0.lowercaseString.containsString("o") ? $1 : nil }.first ?? "Not found"
Run Code Online (Sandbox Code Playgroud)

对于Swift 3:

let dict = ["one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6"]

let results = dict.flatMap { (key, value) in key.lowercased().contains("o") ? value : nil }

print(results)
print(results.first ?? "Not Found")
Run Code Online (Sandbox Code Playgroud)

或者,如果你喜欢神秘的一个衬垫:

let first = dict.flatMap { $0.lowercased().contains("o") ? $1 : nil }.first ?? "Not Found"
Run Code Online (Sandbox Code Playgroud)


aya*_*aio 5

你可以使用filter,containsfirst找到"s":

斯威夫特2

if let key = yourDictionary.keys.filter({ $0.lowercaseString.characters.contains("s") }).first, let result = yourDictionary[key] {
    print(result)
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

if let key = yourDictionary.keys.filter({ $0.lowercased().contains("s") }).first, let result = yourDictionary[key] {
    print(result)
}
Run Code Online (Sandbox Code Playgroud)

在评论中,@ Hamish为Swift 3提供了这个极好的选择:而不是

filter({ ... }).first
Run Code Online (Sandbox Code Playgroud)

您可以使用

first(where: { ... })
Run Code Online (Sandbox Code Playgroud)

例:

if let key = yourDictionary.keys.first(where: { $0.lowercased().contains("s") }), let result = yourDictionary[key] {
    print(result)
}
Run Code Online (Sandbox Code Playgroud)