3

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.

Community
  • 1
  • 1
Guig
  • 9,891
  • 7
  • 64
  • 126

2 Answers2

5

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]
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • I see. Still it's weird that things get messy like that. Anyway if I follow your answer, I then gets `JSONSerialization.isValidJSONObject(dict)` to be `false`. Any idea of what's going on? Json has no issue of anything close to strictly typed so I'd except that to be just fine. – Guig Aug 30 '16 at 07:00
  • @Guig that is a different issue which has nothing to do with the problem you had above. could you please ask that as a separate question on SO? – Ozgur Vatansever Aug 30 '16 at 07:18
  • Sure thing. Here it is: http://stackoverflow.com/questions/39221541/swift-dictionary-with-nil-value-to-json – Guig Aug 30 '16 at 07:40
  • I think the problem is not Guig is trying to add nil into dictionary but it is the new Swift compiler doesn't allow the usage of literal dictionary for `AnyObject` – xi.lin Sep 15 '16 at 06:13
0

Alternatively, splitting things up works as well:

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

var dict = [String : Any]()
dict["_id"] = "123"
dict["profile"] = insideDict
Joshua Wolff
  • 2,687
  • 1
  • 25
  • 42