jglasse
jglasse

Reputation: 1206

Swift dictionary of dictionaries

I'm attempting to parse a dictionary of type [String: Any], and I'm unable parse dictionaries within this dictionary as I would expect:

var monsterDictionary = Dictionary<String, Any>()

monsterDictionary["stringTest"] = "I'm a string"
monsterDictionary["numberTest"] = "12345"
monsterDictionary["arrayTest"] = [1,3,4,"five"]
monsterDictionary["dictTest"] = ["key for number": 123.2 , "key for string" : "hello"]
monsterDictionary["foo-values"] = ["foo-type": foo.FooValueType.fooValuePercent, "foo-value": 25]


for fooItem in (monsterDictionary["foo-values"] as! [String: Any])
{
    let fooType = fooItem["tip-type"]

The last assignment generates the following error: "Type '(key: String, value: Any) has no subscript members."

Upvotes: 1

Views: 2945

Answers (1)

Alexander
Alexander

Reputation: 63271

Iterating over a Dictionary yields Key/Value tuples.

If you actually need to iterate over all the keys/values, then you can do so like this:

for (key, value) in (monsterDictionary["foo-values"] as! [String: Any]) {
    print(key, value)
}

If you're just looking to get the value for tip-type, then you can just do this:

let fooValues = (monsterDictionary["foo-values"] as! [String: Any])
let fooType = ["tip-type"] as! foo.FooValueType

Upvotes: 2

Related Questions