【问题标题】:Swift Dictionary access value through subscript throws ErrorSwift Dictionary 通过下标访问值抛出错误
【发布时间】:2017-11-03 18:54:50
【问题描述】:

通过下标语法访问 Swift Dictionary 值会导致错误 Ambiguous reference to member 'subscript'

这里是代码

class Model {

    struct Keys {
        static let type :String = "type" //RowType
        static let details :String = "details"
    }

    var type :RowType = .None
    var details :[Detail] = []

    init(with dictionary:Dictionary<String, Any>) {

        if let type = dictionary[Keys.type] as? String {
            self.type = self.rowTypeFromString(type: type)
        }

        if let detailsObj = dictionary[Keys.details] as? Array { //Error : Ambiguous reference to member 'subscript'


       }
    }

}

如果我在可选绑定结束时删除类型转换as? Array,它编译得很好

我期望details 键的值是Array,我知道我可以使用[String,Any] 而不是Dictionary&lt;Key, Value&gt;,是什么导致了这个问题?

【问题讨论】:

  • as? Array – 作为 what 的数组?

标签: swift dictionary collections


【解决方案1】:

Array 不像 NSArray 那样工作,您需要明确说明您的数组存储的是什么类型。

如果你想在其中存储Detail 对象,正确的语法是Array&lt;Detail&gt; 或简单的[Detail]

if let detailsObj = dictionary[Keys.details] as? Array<Detail> {

}

【讨论】:

    【解决方案2】:

    通过明确指定数组包含的对象的Type 来解决问题,在我的例子中是Array&lt;[String:Any]&gt;

    if let detailsObj = dictionary[Keys.details] as? Array<[String:Any]> { //we should also specify what type is present inside Array
    
    
    }
    

    致谢:@Hamish、@Dávid Pásztor

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 2020-03-28
      • 2012-01-22
      • 2012-02-07
      • 2017-04-29
      • 1970-01-01
      相关资源
      最近更新 更多