Complex Dictionary : Type 'Any' has no subscript members

Playground:


import UIKit

let people = [ [

"name" : "Bob",

"Age" : 35,

"cars" : [

["type" : "Mercedes GL",

"occupancy" : 7,

"mpg" : 21],

["type" : "Mazda",

"occupancy" : 2,

"mpg" : 24] ]

],[

"name" : "Billy",

"Age" : 26,

"cars" : [

["type" : "VW Golf",

"occupancy" : 5,

"mpg" : 30] ]

]

]

print(people[0]["name"]!)

print(people[0]["cars"]![0]["occupancy"])



The was print function gives me Bob's name. However I am struggling to get the occupancy of his Mercedes car. The second print command gives me "Type 'Any' has no subscript members" as an error. How can I extract the data from the above structure?


Many thanks

Accepted Reply

Swift doesn't have a direct natural way of handling heterogenous tree structures built out of collections. The (inferred) type of the "people" variable is [[String: Any]] (an array of dictionaries with strings as keys). That's why you get your error message. To solve it in this case, you should be able to do something like:


(people[0]["cars"] as! [[String: Any]]) [0]["occupancy"]


This involves a runtime check for the type of the "cars" member.


A better way to do this is to declare explicit types for Person and Car, and build your data out of those types.

Replies

Swift doesn't have a direct natural way of handling heterogenous tree structures built out of collections. The (inferred) type of the "people" variable is [[String: Any]] (an array of dictionaries with strings as keys). That's why you get your error message. To solve it in this case, you should be able to do something like:


(people[0]["cars"] as! [[String: Any]]) [0]["occupancy"]


This involves a runtime check for the type of the "cars" member.


A better way to do this is to declare explicit types for Person and Car, and build your data out of those types.