我正在尝试在 swift 中设置一个简单的字典:
var dict = [
"_id": "123",
"profile": [
"name": "me",
"username": nil,
]
] as [String : Any]
然而,Contextual type 'AnyObject' cannot be used with dictionary literal
失败了。正在关注this question ,我尝试用 [String : [String : Any]]
替换 [String : Any]
,但这在逻辑上失败了,因为第一个值的类型是 String
而不是 [String : Any]
。
我只想拥有一些东西来保存我可以表示为 json 的任何类型的数据,而且我可以接受在以后尝试访问它们时必须进行 guard-cast 处理。
最佳答案
Swift 是一种严格类型的语言,所以问题是当你将 nil
添加到字典时,它无法知道它的值是什么类型这样它会提示说类型不明确。
您可以通过执行以下操作来指定字典的键和值的类型:
let profile: [String: AnyObject?] = ["name": "me", "username": nil]
let dict = ["_id": "123", "profile": profile] as [String : Any]
或者,您可以使用 init(dictionaryLiteral:)
创建字典的构造函数:
let dict = [
"_id": "123",
"profile": Dictionary<String, AnyObject?>(dictionaryLiteral: ("name", "me"), ("username", nil))
] as [String : Any]
关于json - 上下文类型 'AnyObject' 不能与字典文字一起使用 - 数据结构不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39219470/