Guig Guig - 1 year ago 82
JSON Question

Contextual type 'AnyObject' cannot be used with dictionary literal - data structure not consistent

I'm trying to setup a simple dictionary in swift:

var dict = [
"_id": "123",
"profile": [
"name": "me",
"username": nil,
] as [String : Any]

However that fails with
Contextual type 'AnyObject' cannot be used with dictionary literal
. Following this question, I've tried replacing
[String : Any]
[String : [String : Any]]
, but that logically fails because the first value is of type
and not
[String : Any]

I'd just want to have something that holds any kind of data I can represent as a json, and I'm fine with having to guard-cast things when trying to access them later on.

Answer Source

Swift is a strictly typed language, so the the problem is that when you add nil to dictionary, it won't be able to know what type its values going to be so it'll complain saying the type is ambiguous.

You can specify the type of keys and values of the dictionary by doing the following:

let profile: [String: AnyObject?] = ["name": "me", "username": nil]    
let dict = ["_id": "123", "profile": profile] as [String : Any]

Alternatively, you can use init(dictionaryLiteral:) constructor to create the dictionary:

let dict = [
  "_id": "123",
  "profile": Dictionary<String, AnyObject?>(dictionaryLiteral: ("name", "me"), ("username", nil))
] as [String : Any]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download