Swift Dictionary访问值通过下标抛出Error

时间:2017-06-02 11:17:55

标签: swift dictionary collections

通过下标语法访问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<Key, Value>,导致问题的原因是什么?< / p>

2 个答案:

答案 0 :(得分:0)

数组不像NSArray那样工作,你明确需要知道你的数组存储的类型。

如果要在其中存储Detail个对象,正确的语法为Array<Detail>或仅[Detail]

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

}

答案 1 :(得分:0)

通过显式指定数组包含的Type对象来解决问题,在我的例子中是Array<[String:Any]>

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


}

致谢:@Hamish,@DávidPásztor

谢谢!