[英]Swift Dictionary access value through subscript throws Error
Accessing a Swift Dictionary
value through subscript syntax is gives error Ambiguous reference to member 'subscript'
通过下标语法访问Swift
Dictionary
值会产生错误Ambiguous reference to member 'subscript'
Here is the code 这是代码
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'
}
}
}
if i remove the type casting as? Array
如果我删除类型转换
as? Array
as? Array
at the end of optional-binding it compiles fine 可选绑定末尾的
as? Array
可以很好地编译
I am expecting the value of details
key to be an Array
, I know that i can use [String,Any]
instead of Dictionary<Key, Value>
, What is causing the issue ? 我期望
details
键的值是一个Array
,我知道我可以使用[String,Any]
代替Dictionary<Key, Value>
,这是什么原因引起的?
Array doesn't work like NSArray, you explicitly need to tell what type your array is storing. 数组不能像NSArray那样工作,您需要明确地告诉您数组存储的类型。
If you want to store Detail
objects in it, the proper syntax is Array<Detail>
or simply [ Detail]
如果要在其中存储
Detail
对象,则正确的语法是Array<Detail>
或只是[ Detail]
if let detailsObj = dictionary[Keys.details] as? Array<Detail> {
}
Issue is solved by explicitly specifying the Type
of objects the array contains, In my case it was Array<[String:Any]>
通过显式指定数组包含的对象
Type
可以解决问题,在我的情况下是Array<[String:Any]>
if let detailsObj = dictionary[Keys.details] as? Array<[String:Any]> { //we should also specify what type is present inside Array
}
Credits: @Hamish, @Dávid Pásztor 鸣谢:@ Hamish,@DávidPásztor
Thanks! 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.