访问 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/