gpt4 book ai didi

Swift Dictionary 通过下标访问值抛出错误

转载 作者:行者123 更新时间:2023-11-30 12:24:59 25 4
gpt4 key购买 nike

访问 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在可选绑定(bind)结束时,它可以正常编译

我期待 details 的值关键是 Array ,我知道我可以使用[String,Any]而不是Dictionary<Key, Value> ,是什么导致了这个问题?

最佳答案

数组不像 NSArray 那样工作,您明确需要告诉数组存储的类型。

如果你想存储Detail其中的对象,正确的语法是 Array<Detail>或者简单地[Detail]

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

}

关于Swift Dictionary 通过下标访问值抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44327624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com