首页 文章

到达字典中的字典数据

提问于
浏览
0

如何在Swift中的下一个字典中找到第二个整数(键)?而且,虽然在它,我怎么会达到第二个字典中的字符串?

var activeCustomers = Dictionary<Int, Dictionary<Int, Dictionary<String, String>>>()

我尝试写(例如)var test:Int = activeCustomers [1] [1]但是没有用 . 它说该词典没有名为下标的成员 .

1 回答

  • 0

    问题是通过其下标访问 Dictionary 会返回 Optional . 你需要先打开它 .

    在Playground(Swift 1.2)上测试此代码有效:

    var activeCustomers = Dictionary<Int, Dictionary<Int, Dictionary<String, String>>>()
    var d1 = ["a": "b", "c": "d"]
    var d2 = [1: d1]
    activeCustomers = [1: d2]
    if let d3 = activeCustomers[1] {
        var d4 = d3[1]
    }
    

    或者,如果您知道字典中存在该键,则可以避免 if let 并直接打开可选项

    var d4 = activeCustomers[1]?[1]
    

相关问题