Reputation: 9140
I am trying to add an array to dictionary but I am getting this error:
Cannot convert value of type '[[String : String]]' to expected dictionary value type 'Array
Here is my implementation:
let dicContent:[String: String] = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"]
var myArray:Array = [[String: String]]()
myArray.append(dicContent)
let mainDict:[String:Array] = ["MainDictionary": myArray]
I get the error on this line let mainDict:[String:Array] = ["MainDictionary": myArray]
Any of you may know why I am getting this error or way around this?
Upvotes: 0
Views: 120
Reputation: 4376
Do not use Array
keyword for defining type of dictionary. Try following to fix your issues:
let dicContent: [String: String] = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"]
var myArray = [[String: String]]()
myArray.append(dicContent)
let mainDict: [String: [[String: String]]] = ["MainDictionary": myArray]
Tho, types of variables can be implicitly defined in this case, so your code can be simplified to following:
let dicContent = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"]
let mainDict = ["MainDictionary": [dicContent]]
Upvotes: 2
Reputation: 11201
The error says, you have declared the mainDict as
let mainDict:[String:Array]
but did not specify what does the Array holds. Either you can try one of the following to fix the issue.
try:
let dicContent:[String: String] = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"]
var myArray = [[String: String]]()
myArray.append(dicContent)
let mainDict:[String:[[String: String]]] = ["MainDictionary": myArray]
or if you want to use the Array keyword, you can do it like:
let dicContent:[String: String] = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"]
var myArray = Array<[String: String]>()
myArray.append(dicContent)
let mainDict:[String:Array<[String:String]>] = ["MainDictionary": myArray]
or simply
let mainDict = ["MainDictionary": myArray]
When you use the Array Keyword, you need to specify what type of objects that array will hold within the < ... >
Upvotes: 2
Reputation: 36
let dicContent:[String: String] = ["Alabama": "Montgomery",
"Alaska":"Juneau","Arizona":"Phoenix"]
var myArray = [[String: String]]()
myArray.append(dicContent)
let mainDict:[String:Any] = ["MainDictionary": myArray]
let getArrayBack = mainDict["MainDictionary"] as! [[String:String]]
Upvotes: 1