Swift:词典词典,无法获得下标

问题描述 投票:0回答:2

我在这里查看了其他下标问题,但我认为它们与我的问题不符。我有词典字典-Dictionary[String:Dictionary[String:String]]

在扩展名中,我想遍历所有值(Dictionary [String:String]并检索其中一个值。

所以我写了这个:

for dictNEO in Array(self.values)  {
    print(dictNEO)
    print(type(of: dictNEO))
    print(dictNEO["approachDate"])
}

并且在最后一个打印行出现此错误:Value of type 'Value' has no subscripts

这是前两个打印行:

["nominalDist": "\"13.58 ", "approachDate": "\"2020-Feb-01 08:18 ± < 00:01\"", "minimumDist": "\"13.58 ", "diameter": "\"92 m -  210 m\"", "name": "\"(2017 AE5)\""]
Dictionary<String, String>

因此,当它看到词典类型时,为什么告诉我它没有下标,我感到困惑。

swift dictionary subscript
2个回答
0
投票
self.values.map { print(type(of: $0)); $0["approachDate"] }

0
投票

[如果您对我的理解是正确的,则将其写为Dictionary的扩展,这意味着self是通用的,并且定义为Dictionary<Key, Value>,而不是您的特定类型,因此在for循环中,您正在遍历数组的[值]。

因此,您需要先输入Value,然后才能将其作为字典访问

if let dictionary = dictNEO as? [String: String] {
    print(dictNEO["approachDate"])
}

但是由于扩展到Dictionary几乎没有意义,因此您可以在其中访问特定键,因此最好将其编写为函数。由于现在字典定义良好,最后一个print

没有问题
func printValuesForSubKey(_ key: String,  _ dict: [String: [String: String]]) {
    for (dictNEO) in dict.values {
        print(dictNEO)
        print(type(of: dictNEO))
        print(dictNEO[key])        
    }
}

注意,我没有解释为什么type(of:)将其识别为[String: String]

© www.soinside.com 2019 - 2024. All rights reserved.