【问题标题】:how to loop through dictionary keys and compare to my Integer in swift如何遍历字典键并快速与我的整数进行比较
【发布时间】:2015-10-03 12:48:52
【问题描述】:

我有一个简短的问题,关于如何遍历字典键并将其键与我的整数进行比较,然后如果键存在则打印出相应的值。

例如,这是我的代码

for(var j = 0; j <= someDictionary.count; j++) {
    if ( someInteger == someDictionary.keys[j] ) {
        someDictioanrysValue = someDictionary.values[j]
        println(someDictioanrysValue)
    }
}

字典中是否有一种方法可以满足我的需求?

【问题讨论】:

    标签: swift for-loop dictionary compare


    【解决方案1】:

    如果我理解您要正确执行的操作,您只是想使用下标 - 不需要 for 循环。

    let dict = [1: "A", 3: "B", 5: "C"]
    let myInt = 3
    
    if let value = dict[myInt] {
        print(value)
    }
    
    // Prints: B
    

    如果您提供的键值不存在,nil 将被返回,因此if let 中的代码将不会被执行。

    如果您对此不熟悉,我真的建议您看看The Swift Programming Language

    【讨论】:

    • 您好 ABakerSmith,感谢您的快速回复!如果我的问题看起来令人困惑,我深表歉意,但我要问的是,如果我有一个 [Int: String] 的字典 dict,并且我有一个 Integer int,如果 dict 有一个与 int 匹配的键(这里使用 if 进行比较),那么我想打印出那个dict的值(dict[int])
    • 你试过我的例子了吗?那应该做你想做的:)
    • 没问题 :) 另外,你认为你能接受这个答案吗?
    猜你喜欢
    • 2021-04-21
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 2020-12-26
    • 2023-04-03
    相关资源
    最近更新 更多