反向Swift字典查询 [英] Reverse Swift dictionary lookup
本文介绍了反向Swift字典查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一本这样的字典:
let ints: [Int: String] = [
0: "0",
1: "1",
2: "2",
3: "3",
4: "4",
5: "5",
6: "6",
7: "7",
8: "8",
9: "9",
10: "A",
11: "B",
// etc...
]
我可以用ints[5]
查找整数以获得"5"
.如何从字符串中查找整数?我想做类似ints.keys["5"]
-> 5
的事情.
I can look up an integer with ints[5]
to get "5"
. How can I look up the integer from the string? I want to do something like ints.keys["5"]
-> 5
.
此刻,我刚刚向后写了字典:
At the moment, I have just written the dictionary backwards:
let chars: [String: Int] = [
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"A": 10,
"B": 11,
// etc...
]
我可以做chars["5"]
来获得5
,但这是一个麻烦的解决方案,因为我的字典很大,并且希望能够在需要时轻松地对其进行更改.
I can do chars["5"]
to get 5
, but this is a cumbersome solution since my dictionary is big and want to be able to change it easily if needed.
我不想以编程方式构造字典,而只保留一个硬编码.
I don't want to programmatically construct the dictionaries, but just keep one hard coded.
推荐答案
我使用Martin R的链接来找到此解决方案:
I used Martin R's link to find this solution:
let int = 11
print(chars.filter{$1 == int}.map{$0.0}[0]) // B
这篇关于反向Swift字典查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文