【问题标题】:Swift: Dictionary of Dicitionaries, cannot get subscriptSwift:字典词典,无法获取下标
【发布时间】:2020-05-04 19:55:06
【问题描述】:

我在这里查看了其他下标问题,但我认为它们与我的问题不符。我有一本字典 - 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?这应该可以帮助人们帮助你。

标签: swift dictionary subscript


【解决方案1】:

如果我理解正确,您已将其编写为 Dictionary 的扩展,这意味着 self 是通用的并定义为 Dictionary&lt;Key, Value&gt; 而不是您的特定类型,因此在您的 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]

【讨论】:

  • 关于最后一句话:编译时已知的类型与运行时的实际类型之间的差异可以解释这一点。
【解决方案2】:

代码 sn-p 不起作用,因为values 属性是集合的集合,而使用Array(values) 您可以创建集合集合的集合。简而言之,代码往下走,而是往上走并创建新的集合级别。

  • 使用Higher order function map 的解决方案:

    self.values.map { print(type(of: $0)); $0["approachDate"] }
    
  • For-In Loop的解决方案

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

【讨论】:

  • 虽然此代码可能有效,但它是否回答“所以我很困惑为什么它在将类型视为字典时告诉我它没有下标”?您可能希望编辑您的答案并说明为什么您的版本有效而​​原始版本无效。
  • dictNEO的类型是(或者应该是)Array&lt;[String : String]&gt;,没有“collection of collections”等
  • 在 For-in 循环之前复制粘贴 print(type(of: values)) 的结果
  • 这就是我得到类型的方式,如果是从操场上复制的,否则我会写 [[String : String]] ;-) 请参阅 Joakim Danielson 的诊断答案。
  • 所以,在这里复制并粘贴更多代码:类和游乐场 sn-p
猜你喜欢
  • 2022-06-29
  • 1970-01-01
  • 2016-02-12
  • 2022-12-17
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
相关资源
最近更新 更多