Dictionary 根据value获取key

Dictionary 可以根据key获得value,可是如何根据value获取key呢?

以下是个人整理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import UIKit
import Foundation

// http://stackoverflow.com/questions/27218669/swift-dictionary-get-key-for-value
// Dictionary 根据value获取key
extension Dictionary where Value : Equatable {
func allKeysForValue(val : Value) -> [Key] {
return self.filter { $1 == val }.map { $0.0 }
}


func someKeyFor(value: Value) -> Key? {
guard let index = indexOf({ $0.1 == value }) else {
return nil
}
return self[index].0
}
}


func allKeysForValue222<K, V : Equatable>(dict: [K : V], val: V) -> [K] {
return dict.filter{ $0.1 == val }.map{ $0.0 }
}

let dict = ["a" : 1, "b" : 2, "c" : 1, "d" : 2]

dict.allKeysForValue(1)

dict.someKeyFor(1)

allKeysForValue222(dict, val: 1)

参考文章:
http://stackoverflow.com/questions/27218669/swift-dictionary-get-key-for-value

本文标题:Dictionary 根据value获取key

文章作者:史彦超

发布时间:2016年10月11日 - 22:10

最后更新:2021年07月20日 - 16:07

原始链接:https://doingself.github.io/2016/10/11/2016-10-11-Dictionary%E6%A0%B9%E6%8D%AEvalue%E8%8E%B7%E5%8F%96key/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Donate comment here