【问题标题】:Array and dictionary, what's the correct syntax of loop?数组和字典,循环的正确语法是什么?
【发布时间】:2016-10-07 18:32:29
【问题描述】:

array dictionary 中的循环有问题。我需要这样的东西。如何检查字符串数组的项是否等于messagesDictionary的项:

var stringArray = ["first","second","third"]
var messagesDictionary = [["first": 50],["second": 60],["third": 70]]

    for item in stringArray {
        for itemDic in messagesDictionary {
            if item == itemDic[key] { // this 'itemDic[key]' wrong

            }
        }
    }

这个循环的正确语法是什么?

【问题讨论】:

  • 你到底想做什么?您有一系列要循环的字典。您是否尝试查看某个键是否存在特定值?或者您是否也尝试遍历每个单独的字典?
  • 你需要遍历你的messagesDictionary中的每个字典for (key, value) in itemDic {

标签: arrays swift loops dictionary


【解决方案1】:

改为这样迭代:

let stringArray:[String]  = ["first","second","third"]
let messagesDictionary: [[String: Any]] = [["first": 50],["second": 60],["third": 70]]
for item in stringArray {
    for itemDic in messagesDictionary {
        for (key, value) in itemDic {
            if item == key {

            }

        }
    }
}

【讨论】:

  • 我试过了。我得到:“表达式类型 '[[String:Int]]' 在没有更多上下文的情况下是模棱两可的”
  • 伟大的@DenisWindover。您应该考虑接受答案,以便其他人将来可以从中受益。只需单击我的答案中投票下方的复选标记即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
相关资源
最近更新 更多