0

I am trying to create a array to hold dictionaries.

var deaultScoreResults : [Dictionary<String, Int>] = [];

But when I try to add a dictionary key:value pair I get:

deaultScoreResults.append(["Study Up!", 1]);

Error;

Type 'Dictionary' does not conform to protocol 'ArrayLiteralConvertible'

nhgrif
  • 61,578
  • 25
  • 134
  • 173
dancingbush
  • 2,131
  • 5
  • 30
  • 66

2 Answers2

4

Square brackets surrounding a comma separated list of values is an array literal.

["this", "is", "a", "swift", "literal", "array"]

For a literal dictionary, you need a comma separated list of key:value pairs:

[1:"this", 2:"is", 3:"a", 4:"swift", 5:"literal", 6:"dictionary"]

To fix the error, you simply need to change your comma to a colon:

defaultScoreResults.append(["Study Up!":1])

However, based on your previous question, I'm going to assume an array of <String, Int> dictionaries isn't anywhere near what you're looking for.

I would suggest that you want simply an <Int, String> dictionary:

var defaultScoreResults = Dictionary<Int, String>()
defaultScoreResults[1] = "Study Up!"
Community
  • 1
  • 1
nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • Ha you read my mind that is exactly what I spent last hour getting my head around, trial and error, cheers again – dancingbush Apr 02 '15 at 23:25
  • So what is the difference bewteen var deaultScoreResults : [Dictionary] = []; and var deaultScoreResults = [DictionaryString, Int>] ()? – dancingbush Apr 03 '15 at 05:58
  • @dancingbush in practice, nothing. They both do the same thing. I think the latter looks a lot better though. – nhgrif Apr 03 '15 at 10:31
1

Try this:

var deaultScoreResults = [Dictionary<String, Int>]()
deaultScoreResults.append(["Study Up!":1])

You could also declare it like this:

var deaultScoreResults = [[String:Int]]()
Eric Aya
  • 69,473
  • 35
  • 181
  • 253