Hello,
Please can you tell me how to create an array of dictionaries? This code below should create 4 dictionaries in an array, but I'm getting these errors:
For line "var output = [id: "testID", name: "testName"]":
cannot find 'name' in scope Type '(any AnyObject).Type'
cannot conform to 'Hashable'
For line "return output":
Type '(any AnyObject).Type' cannot conform to 'Hashable'
var quotes: [(id: String, name: String)] {
var output = [[(id: String, name: String)]] ()
for i in 1...4 {
var output = [id: "testID", name: "testName"]
}
return output
}
There were several mistakes:
[(id: String, name: String)]
This is not a good definition of a dictionary, which is just [key:value], no labels
var output = [id: "testID", name: "testName"]
It does not make sense. If you wrote
var output = ["id": "testID", "name": "testName"]
that would be a dictionary with 2 elements, but that's not what you need here
In your loop, you replace output at each iteration. So at the end you get only the 4th input.
for i in 1...4 {
var output = [id: "testID", name: "testName"]
}
Here is a correct code. I created a type alias for better readability.
typealias MyDict = [String: String] // A dictionary is defined as [key:Value]
var quotes: [MyDict] {
var allQuotes = [MyDict]() // Creates an empty array
for i in 1...4 {
var newOutput = ["testID" : "testName \(i)", "secondID" : "secondName \(i)"] // a dict with 2 pairs allQuotes.append(newOutput) // We append the new output to the array of Dicts
}
return allQuotes
}
print(quotes)
And you get the expected array:
[["secondID": "secondName 1", "testID": "testName 1"], ["testID": "testName 2", "secondID": "secondName 2"], ["testID": "testName 3", "secondID": "secondName 3"], ["secondID": "secondName 4", "testID": "testName 4"]]
Note that as always in dictionaries, the order of pairs is never guaranteed
If you ask for an item:
print(quotes[0]["testID"])
you get an optional (as the value for the key is nil if there is no value)
Optional("testName 1")
So you should write:
print(quotes[0]["testID"] ?? "not found")
and get:
testName 1