Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

swift2

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

like image 275
Andre M Avatar asked Feb 26 '16 22:02

Andre M


1 Answers

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]]() 
like image 175
vadian Avatar answered Oct 07 '22 00:10

vadian