反向 Swift 字典查找

twh*_*mon 2 arrays dictionary 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...
]
Run Code Online (Sandbox Code Playgroud)

我可以查找一个整数ints[5]来获取"5"。如何从字符串中查找整数?我想做类似ints.keys["5"]-> 的事情5

目前,我刚刚把字典倒过来写了:

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...
]
Run Code Online (Sandbox Code Playgroud)

我能做chars["5"]得到5,但是这是一个麻烦的解决方案,因为我的字典里是大,希望能够在需要时轻松地改变它。

澄清

我不想以编程方式构建字典,而只想保留一个硬编码。

Cri*_*tik 5

您可以利用 Swift 字典实现Collection协议的事实,该协议扩展了协议Sequence,并使用first返回匹配给定条件的序列的第一个元素的方法:

extension Dictionary where Value: Equatable {
    func key(forValue value: Value) -> Key? {
        return first { $0.1 == value }?.0
    }
}

ints.key(forValue: "5")    // 5
ints.key(forValue: "99")   // nil
Run Code Online (Sandbox Code Playgroud)

上面的代码Dictionary可以被同化为一系列(Key, Value)对。唯一需要注意的是,如果多个键匹配相同的值,我们只会得到这些键中的一个,并且不能确定是哪一个——尽管如果你的字典有一对一的映射,你就没有这个问题。


twh*_*mon 1

我使用 Martin R 的链接找到了这个解决方案:

let int = 11
print(chars.filter{$1 == int}.map{$0.0}[0]) // B
Run Code Online (Sandbox Code Playgroud)