问题描述
我正在使用 [UIImage:UIImage] 类型的 swift 字典,并且我正在尝试为给定值查找特定键.在 Objective-C 中,我可以使用 allKeysForValue,但对于 Swift 字典似乎没有这样的方法.我应该使用什么?
I'm using a swift dictionary of type [UIImage:UIImage], and I'm trying to find a specific key for a given value. In Objective-C I could use allKeysForValue, but there appears to be no such method for a Swift dictionary. What should I be using?
推荐答案
Swift 3:一种针对双射词典特殊情况的更高效方法
如果反向字典查找用例涵盖键和值之间具有一对一关系的双射字典,则集合穷举filter
操作的另一种方法是使用更快的短路找到某些键(如果存在)的方法.
Swift 3: a more performant approach for the special case of bijective dictionaries
If the reverse dictionary lookup use case covers a bijective dictionary with a one to one relationship between keys and values, an alternative approach to the collection-exhaustive filter
operation would be using a quicker short-circuiting approach to find some key, if it exists.
extension Dictionary where Value: Equatable {
func someKey(forValue val: Value) -> Key? {
return first(where: { $1 == val })?.key
}
}
示例用法:
let dict: [Int: String] = [1: "one", 2: "two", 4: "four"]
if let key = dict.someKey(forValue: "two") {
print(key)
} // 2
这篇关于Swift 字典获取值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!