Andre M
Andre M

Reputation: 7534

Contextual type 'AnyObject' cannot be used with dictionary literal?

I am in the process of trying to convert an Objective-C example to Swift 2, but I am running into a small issue. The original Objective-C snippet:

NSMutableArray *inputsOutputs = [NSMutableArray array];
...
[inputsOutputs addObject:@{@"input" : input, @"output" : trackOutput}];

and what I thought the Swift code should be:

var inputsOutputs = [Any?]()
...
inputsOutputs.append([ "input": input, "output": trackOutput ])

The resultant error is:

Contextual type 'AnyObject' cannot be used with dictionary literal?

How would I convert the Objective-C in this case to Swift?

Original Objective-C: https://developer.apple.com/library/mac/samplecode/avsubtitleswriterOSX/Listings/avsubtitleswriter_main_m.html

Upvotes: 31

Views: 39777

Answers (2)

vadian
vadian

Reputation: 285069

You can see that the contents of the array are dictionaries with String keys and unknown values.

Therefore declare the array more specific

var inputsOutputs = [[String:AnyObject]]()

In Swift 3 for JSON collection types or if the dictionary / array contains only value types use

var inputsOutputs = [[String:Any]]()

Upvotes: 37

NRitH
NRitH

Reputation: 13893

It should be just fine, at least in Swift 2+. I just tried the following in a playground:

var objects = [Any?]()
let dict = [ "one" : 1, "two" : 2 ]
objects.append(dict)  // prints [{["one": 1, "two": 2]}]
objects.append([ "one" : 1, "two" : 2 ]) // prints [{["one": 1, "two": 2]}, {["one": 1, "two": 2]}]

Upvotes: 4

Related Questions