Guig
Guig

Reputation: 10187

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] by [String : [String : Any]], but that logically fails because the first value is of type String 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.

Upvotes: 3

Views: 2701

Answers (2)

Joshua Wolff
Joshua Wolff

Reputation: 3352

Alternatively, splitting things up works as well:

let insideDict = [
    "name": "me",
    "username": nil,
  ]

var dict = [String : Any]()
dict["_id"] = "123"
dict["profile"] = insideDict

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52103

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]

Upvotes: 5

Related Questions